es6.js 4.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines The current define statements for the shader.
  65. * @returns The resulting defines with defines of the current rank removed.
  66. */
  67. EffectFallbacks.prototype.reduce = function (currentDefines) {
  68. // First we try to switch to CPU skinning
  69. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  70. this._mesh.computeBonesUsingShaders = false;
  71. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  72. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  73. var scene = this._mesh.getScene();
  74. for (var index = 0; index < scene.meshes.length; index++) {
  75. var otherMesh = scene.meshes[index];
  76. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  77. otherMesh.computeBonesUsingShaders = false;
  78. }
  79. }
  80. }
  81. else {
  82. var currentFallbacks = this._defines[this._currentRank];
  83. if (currentFallbacks) {
  84. for (var index = 0; index < currentFallbacks.length; index++) {
  85. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  86. }
  87. }
  88. this._currentRank++;
  89. }
  90. return currentDefines;
  91. };
  92. return EffectFallbacks;
  93. }());
  94. BABYLON.EffectFallbacks = EffectFallbacks;
  95. /**
  96. * Options to be used when creating an effect.
  97. */
  98. var EffectCreationOptions = /** @class */ (function () {
  99. function EffectCreationOptions() {
  100. }
  101. return EffectCreationOptions;
  102. }());
  103. BABYLON.EffectCreationOptions = EffectCreationOptions;
  104. /**
  105. * Effect containing vertex and fragment shader that can be executed on an object.
  106. */
  107. var Effect = /** @class */ (function () {
  108. /**
  109. * Instantiates an effect.
  110. * An effect can be used to create/manage/execute vertex and fragment shaders.
  111. * @param baseName Name of the effect.
  112. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  113. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  114. * @param samplers List of sampler variables that will be passed to the shader.
  115. * @param engine Engine to be used to render the effect
  116. * @param defines Define statements to be added to the shader.
  117. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  118. * @param onCompiled Callback that will be called when the shader is compiled.
  119. * @param onError Callback that will be called if an error occurs during shader compilation.
  120. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  121. */
  122. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  123. if (samplers === void 0) { samplers = null; }
  124. if (defines === void 0) { defines = null; }
  125. if (fallbacks === void 0) { fallbacks = null; }
  126. if (onCompiled === void 0) { onCompiled = null; }
  127. if (onError === void 0) { onError = null; }
  128. var _this = this;
  129. /**
  130. * Unique ID of the effect.
  131. */
  132. this.uniqueId = 0;
  133. /**
  134. * Observable that will be called when the shader is compiled.
  135. */
  136. this.onCompileObservable = new BABYLON.Observable();
  137. /**
  138. * Observable that will be called if an error occurs during shader compilation.
  139. */
  140. this.onErrorObservable = new BABYLON.Observable();
  141. /**
  142. * Observable that will be called when effect is bound.
  143. */
  144. this.onBindObservable = new BABYLON.Observable();
  145. this._uniformBuffersNames = {};
  146. this._isReady = false;
  147. this._compilationError = "";
  148. this.name = baseName;
  149. if (attributesNamesOrOptions.attributes) {
  150. var options = attributesNamesOrOptions;
  151. this._engine = uniformsNamesOrEngine;
  152. this._attributesNames = options.attributes;
  153. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  154. this._samplers = options.samplers;
  155. this.defines = options.defines;
  156. this.onError = options.onError;
  157. this.onCompiled = options.onCompiled;
  158. this._fallbacks = options.fallbacks;
  159. this._indexParameters = options.indexParameters;
  160. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  161. if (options.uniformBuffersNames) {
  162. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  163. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  164. }
  165. }
  166. }
  167. else {
  168. this._engine = engine;
  169. this.defines = defines;
  170. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  171. this._samplers = samplers;
  172. this._attributesNames = attributesNamesOrOptions;
  173. this.onError = onError;
  174. this.onCompiled = onCompiled;
  175. this._indexParameters = indexParameters;
  176. this._fallbacks = fallbacks;
  177. }
  178. this.uniqueId = Effect._uniqueIdSeed++;
  179. var vertexSource;
  180. var fragmentSource;
  181. if (baseName.vertexElement) {
  182. vertexSource = document.getElementById(baseName.vertexElement);
  183. if (!vertexSource) {
  184. vertexSource = baseName.vertexElement;
  185. }
  186. }
  187. else {
  188. vertexSource = baseName.vertex || baseName;
  189. }
  190. if (baseName.fragmentElement) {
  191. fragmentSource = document.getElementById(baseName.fragmentElement);
  192. if (!fragmentSource) {
  193. fragmentSource = baseName.fragmentElement;
  194. }
  195. }
  196. else {
  197. fragmentSource = baseName.fragment || baseName;
  198. }
  199. var finalVertexCode;
  200. this._loadVertexShaderAsync(vertexSource)
  201. .then(function (vertexCode) {
  202. return _this._processIncludesAsync(vertexCode);
  203. })
  204. .then(function (vertexCodeWithIncludes) {
  205. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  206. return _this._loadFragmentShaderAsync(fragmentSource);
  207. })
  208. .then(function (fragmentCode) {
  209. return _this._processIncludesAsync(fragmentCode);
  210. })
  211. .then(function (fragmentCodeWithIncludes) {
  212. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  213. if (baseName) {
  214. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  215. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  216. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  217. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  218. }
  219. else {
  220. _this._vertexSourceCode = finalVertexCode;
  221. _this._fragmentSourceCode = migratedFragmentCode;
  222. }
  223. _this._prepareEffect();
  224. });
  225. }
  226. Object.defineProperty(Effect.prototype, "key", {
  227. /**
  228. * Unique key for this effect
  229. */
  230. get: function () {
  231. return this._key;
  232. },
  233. enumerable: true,
  234. configurable: true
  235. });
  236. /**
  237. * If the effect has been compiled and prepared.
  238. * @returns if the effect is compiled and prepared.
  239. */
  240. Effect.prototype.isReady = function () {
  241. return this._isReady;
  242. };
  243. /**
  244. * The engine the effect was initialized with.
  245. * @returns the engine.
  246. */
  247. Effect.prototype.getEngine = function () {
  248. return this._engine;
  249. };
  250. /**
  251. * The compiled webGL program for the effect
  252. * @returns the webGL program.
  253. */
  254. Effect.prototype.getProgram = function () {
  255. return this._program;
  256. };
  257. /**
  258. * The set of names of attribute variables for the shader.
  259. * @returns An array of attribute names.
  260. */
  261. Effect.prototype.getAttributesNames = function () {
  262. return this._attributesNames;
  263. };
  264. /**
  265. * Returns the attribute at the given index.
  266. * @param index The index of the attribute.
  267. * @returns The location of the attribute.
  268. */
  269. Effect.prototype.getAttributeLocation = function (index) {
  270. return this._attributes[index];
  271. };
  272. /**
  273. * Returns the attribute based on the name of the variable.
  274. * @param name of the attribute to look up.
  275. * @returns the attribute location.
  276. */
  277. Effect.prototype.getAttributeLocationByName = function (name) {
  278. var index = this._attributesNames.indexOf(name);
  279. return this._attributes[index];
  280. };
  281. /**
  282. * The number of attributes.
  283. * @returns the numnber of attributes.
  284. */
  285. Effect.prototype.getAttributesCount = function () {
  286. return this._attributes.length;
  287. };
  288. /**
  289. * Gets the index of a uniform variable.
  290. * @param uniformName of the uniform to look up.
  291. * @returns the index.
  292. */
  293. Effect.prototype.getUniformIndex = function (uniformName) {
  294. return this._uniformsNames.indexOf(uniformName);
  295. };
  296. /**
  297. * Returns the attribute based on the name of the variable.
  298. * @param uniformName of the uniform to look up.
  299. * @returns the location of the uniform.
  300. */
  301. Effect.prototype.getUniform = function (uniformName) {
  302. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  303. };
  304. /**
  305. * Returns an array of sampler variable names
  306. * @returns The array of sampler variable neames.
  307. */
  308. Effect.prototype.getSamplers = function () {
  309. return this._samplers;
  310. };
  311. /**
  312. * The error from the last compilation.
  313. * @returns the error string.
  314. */
  315. Effect.prototype.getCompilationError = function () {
  316. return this._compilationError;
  317. };
  318. /**
  319. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  320. * @param func The callback to be used.
  321. */
  322. Effect.prototype.executeWhenCompiled = function (func) {
  323. if (this.isReady()) {
  324. func(this);
  325. return;
  326. }
  327. this.onCompileObservable.add(function (effect) {
  328. func(effect);
  329. });
  330. };
  331. /** @ignore */
  332. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  333. if (BABYLON.Tools.IsWindowObjectExist()) {
  334. // DOM element ?
  335. if (vertex instanceof HTMLElement) {
  336. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  337. return Promise.resolve(vertexCode);
  338. }
  339. }
  340. // Base64 encoded ?
  341. if (vertex.substr(0, 7) === "base64:") {
  342. var vertexBinary = window.atob(vertex.substr(7));
  343. return Promise.resolve(vertexBinary);
  344. }
  345. // Is in local store ?
  346. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  347. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  348. }
  349. var vertexShaderUrl;
  350. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  351. vertexShaderUrl = vertex;
  352. }
  353. else {
  354. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  355. }
  356. // Vertex shader
  357. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  358. };
  359. /** @ignore */
  360. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  361. if (BABYLON.Tools.IsWindowObjectExist()) {
  362. // DOM element ?
  363. if (fragment instanceof HTMLElement) {
  364. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  365. return Promise.resolve(fragmentCode);
  366. }
  367. }
  368. // Base64 encoded ?
  369. if (fragment.substr(0, 7) === "base64:") {
  370. var fragmentBinary = window.atob(fragment.substr(7));
  371. return Promise.resolve(fragmentBinary);
  372. }
  373. // Is in local store ?
  374. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  375. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  376. }
  377. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  378. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  379. }
  380. var fragmentShaderUrl;
  381. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  382. fragmentShaderUrl = fragment;
  383. }
  384. else {
  385. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  386. }
  387. // Fragment shader
  388. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  389. };
  390. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  391. // Rebuild shaders source code
  392. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  393. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  394. vertexCode = prefix + vertexCode;
  395. fragmentCode = prefix + fragmentCode;
  396. // Number lines of shaders source code
  397. var i = 2;
  398. var regex = /\n/gm;
  399. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  400. i = 2;
  401. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  402. // Dump shaders name and formatted source code
  403. if (this.name.vertexElement) {
  404. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  405. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  406. }
  407. else if (this.name.vertex) {
  408. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  409. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  410. }
  411. else {
  412. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  413. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  414. }
  415. };
  416. ;
  417. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  418. var preparedSourceCode = this._processPrecision(sourceCode);
  419. if (this._engine.webGLVersion == 1) {
  420. return preparedSourceCode;
  421. }
  422. // Already converted
  423. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  424. return preparedSourceCode.replace("#version 300 es", "");
  425. }
  426. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  427. // Remove extensions
  428. // #extension GL_OES_standard_derivatives : enable
  429. // #extension GL_EXT_shader_texture_lod : enable
  430. // #extension GL_EXT_frag_depth : enable
  431. // #extension GL_EXT_draw_buffers : require
  432. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  433. var result = preparedSourceCode.replace(regex, "");
  434. // Migrate to GLSL v300
  435. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  436. result = result.replace(/attribute[ \t]/g, "in ");
  437. result = result.replace(/[ \t]attribute/g, " in");
  438. if (isFragment) {
  439. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  440. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  441. result = result.replace(/texture2D\s*\(/g, "texture(");
  442. result = result.replace(/textureCube\s*\(/g, "texture(");
  443. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  444. result = result.replace(/gl_FragColor/g, "glFragColor");
  445. result = result.replace(/gl_FragData/g, "glFragData");
  446. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  447. }
  448. return result;
  449. };
  450. Effect.prototype._processIncludesAsync = function (sourceCode) {
  451. var _this = this;
  452. return new Promise(function (resolve, reject) {
  453. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  454. var match = regex.exec(sourceCode);
  455. var returnValue = sourceCode;
  456. while (match != null) {
  457. var includeFile = match[1];
  458. // Uniform declaration
  459. if (includeFile.indexOf("__decl__") !== -1) {
  460. includeFile = includeFile.replace(/__decl__/, "");
  461. if (_this._engine.supportsUniformBuffers) {
  462. includeFile = includeFile.replace(/Vertex/, "Ubo");
  463. includeFile = includeFile.replace(/Fragment/, "Ubo");
  464. }
  465. includeFile = includeFile + "Declaration";
  466. }
  467. if (Effect.IncludesShadersStore[includeFile]) {
  468. // Substitution
  469. var includeContent = Effect.IncludesShadersStore[includeFile];
  470. if (match[2]) {
  471. var splits = match[3].split(",");
  472. for (var index = 0; index < splits.length; index += 2) {
  473. var source = new RegExp(splits[index], "g");
  474. var dest = splits[index + 1];
  475. includeContent = includeContent.replace(source, dest);
  476. }
  477. }
  478. if (match[4]) {
  479. var indexString = match[5];
  480. if (indexString.indexOf("..") !== -1) {
  481. var indexSplits = indexString.split("..");
  482. var minIndex = parseInt(indexSplits[0]);
  483. var maxIndex = parseInt(indexSplits[1]);
  484. var sourceIncludeContent = includeContent.slice(0);
  485. includeContent = "";
  486. if (isNaN(maxIndex)) {
  487. maxIndex = _this._indexParameters[indexSplits[1]];
  488. }
  489. for (var i = minIndex; i < maxIndex; i++) {
  490. if (!_this._engine.supportsUniformBuffers) {
  491. // Ubo replacement
  492. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  493. return p1 + "{X}";
  494. });
  495. }
  496. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  497. }
  498. }
  499. else {
  500. if (!_this._engine.supportsUniformBuffers) {
  501. // Ubo replacement
  502. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  503. return p1 + "{X}";
  504. });
  505. }
  506. includeContent = includeContent.replace(/\{X\}/g, indexString);
  507. }
  508. }
  509. // Replace
  510. returnValue = returnValue.replace(match[0], includeContent);
  511. }
  512. else {
  513. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  514. _this._engine._loadFileAsync(includeShaderUrl)
  515. .then(function (fileContent) {
  516. Effect.IncludesShadersStore[includeFile] = fileContent;
  517. return _this._processIncludesAsync(returnValue);
  518. })
  519. .then(function (returnValue) {
  520. resolve(returnValue);
  521. });
  522. return;
  523. }
  524. match = regex.exec(sourceCode);
  525. }
  526. resolve(returnValue);
  527. });
  528. };
  529. Effect.prototype._processPrecision = function (source) {
  530. if (source.indexOf("precision highp float") === -1) {
  531. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  532. source = "precision mediump float;\n" + source;
  533. }
  534. else {
  535. source = "precision highp float;\n" + source;
  536. }
  537. }
  538. else {
  539. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  540. source = source.replace("precision highp float", "precision mediump float");
  541. }
  542. }
  543. return source;
  544. };
  545. /**
  546. * Recompiles the webGL program
  547. * @param vertexSourceCode The source code for the vertex shader.
  548. * @param fragmentSourceCode The source code for the fragment shader.
  549. * @param onCompiled Callback called when completed.
  550. * @param onError Callback called on error.
  551. */
  552. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  553. var _this = this;
  554. this._isReady = false;
  555. this._vertexSourceCodeOverride = vertexSourceCode;
  556. this._fragmentSourceCodeOverride = fragmentSourceCode;
  557. this.onError = function (effect, error) {
  558. if (onError) {
  559. onError(error);
  560. }
  561. };
  562. this.onCompiled = function () {
  563. var scenes = _this.getEngine().scenes;
  564. for (var i = 0; i < scenes.length; i++) {
  565. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  566. }
  567. if (onCompiled) {
  568. onCompiled(_this._program);
  569. }
  570. };
  571. this._fallbacks = null;
  572. this._prepareEffect();
  573. };
  574. /**
  575. * Gets the uniform locations of the the specified variable names
  576. * @param names THe names of the variables to lookup.
  577. * @returns Array of locations in the same order as variable names.
  578. */
  579. Effect.prototype.getSpecificUniformLocations = function (names) {
  580. var engine = this._engine;
  581. return engine.getUniforms(this._program, names);
  582. };
  583. /**
  584. * Prepares the effect
  585. */
  586. Effect.prototype._prepareEffect = function () {
  587. var attributesNames = this._attributesNames;
  588. var defines = this.defines;
  589. var fallbacks = this._fallbacks;
  590. this._valueCache = {};
  591. var previousProgram = this._program;
  592. try {
  593. var engine = this._engine;
  594. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  595. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  596. }
  597. else {
  598. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  599. }
  600. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  601. if (engine.supportsUniformBuffers) {
  602. for (var name in this._uniformBuffersNames) {
  603. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  604. }
  605. }
  606. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  607. this._attributes = engine.getAttributes(this._program, attributesNames);
  608. var index;
  609. for (index = 0; index < this._samplers.length; index++) {
  610. var sampler = this.getUniform(this._samplers[index]);
  611. if (sampler == null) {
  612. this._samplers.splice(index, 1);
  613. index--;
  614. }
  615. }
  616. engine.bindSamplers(this);
  617. this._compilationError = "";
  618. this._isReady = true;
  619. if (this.onCompiled) {
  620. this.onCompiled(this);
  621. }
  622. this.onCompileObservable.notifyObservers(this);
  623. this.onCompileObservable.clear();
  624. // Unbind mesh reference in fallbacks
  625. if (this._fallbacks) {
  626. this._fallbacks.unBindMesh();
  627. }
  628. if (previousProgram) {
  629. this.getEngine()._deleteProgram(previousProgram);
  630. }
  631. }
  632. catch (e) {
  633. this._compilationError = e.message;
  634. // Let's go through fallbacks then
  635. BABYLON.Tools.Error("Unable to compile effect:");
  636. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  637. return " " + uniform;
  638. }));
  639. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  640. return " " + attribute;
  641. }));
  642. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  643. BABYLON.Tools.Error("Error: " + this._compilationError);
  644. if (previousProgram) {
  645. this._program = previousProgram;
  646. this._isReady = true;
  647. if (this.onError) {
  648. this.onError(this, this._compilationError);
  649. }
  650. this.onErrorObservable.notifyObservers(this);
  651. }
  652. if (fallbacks && fallbacks.isMoreFallbacks) {
  653. BABYLON.Tools.Error("Trying next fallback.");
  654. this.defines = fallbacks.reduce(this.defines);
  655. this._prepareEffect();
  656. }
  657. else {
  658. if (this.onError) {
  659. this.onError(this, this._compilationError);
  660. }
  661. this.onErrorObservable.notifyObservers(this);
  662. this.onErrorObservable.clear();
  663. // Unbind mesh reference in fallbacks
  664. if (this._fallbacks) {
  665. this._fallbacks.unBindMesh();
  666. }
  667. }
  668. }
  669. };
  670. Object.defineProperty(Effect.prototype, "isSupported", {
  671. /**
  672. * Checks if the effect is supported. (Must be called after compilation)
  673. */
  674. get: function () {
  675. return this._compilationError === "";
  676. },
  677. enumerable: true,
  678. configurable: true
  679. });
  680. /**
  681. * Binds a texture to the engine to be used as output of the shader.
  682. * @param channel Name of the output variable.
  683. * @param texture Texture to bind.
  684. */
  685. Effect.prototype._bindTexture = function (channel, texture) {
  686. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  687. };
  688. /**
  689. * Sets a texture on the engine to be used in the shader.
  690. * @param channel Name of the sampler variable.
  691. * @param texture Texture to set.
  692. */
  693. Effect.prototype.setTexture = function (channel, texture) {
  694. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  695. };
  696. /**
  697. * Sets an array of textures on the engine to be used in the shader.
  698. * @param channel Name of the variable.
  699. * @param textures Textures to set.
  700. */
  701. Effect.prototype.setTextureArray = function (channel, textures) {
  702. if (this._samplers.indexOf(channel + "Ex") === -1) {
  703. var initialPos = this._samplers.indexOf(channel);
  704. for (var index = 1; index < textures.length; index++) {
  705. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  706. }
  707. }
  708. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  709. };
  710. /**
  711. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  712. * @param channel Name of the sampler variable.
  713. * @param postProcess Post process to get the input texture from.
  714. */
  715. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  716. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  717. };
  718. /** @ignore */
  719. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  720. var cache = this._valueCache[uniformName];
  721. var flag = matrix.updateFlag;
  722. if (cache !== undefined && cache === flag) {
  723. return false;
  724. }
  725. this._valueCache[uniformName] = flag;
  726. return true;
  727. };
  728. /** @ignore */
  729. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  730. var cache = this._valueCache[uniformName];
  731. if (!cache) {
  732. cache = [x, y];
  733. this._valueCache[uniformName] = cache;
  734. return true;
  735. }
  736. var changed = false;
  737. if (cache[0] !== x) {
  738. cache[0] = x;
  739. changed = true;
  740. }
  741. if (cache[1] !== y) {
  742. cache[1] = y;
  743. changed = true;
  744. }
  745. return changed;
  746. };
  747. /** @ignore */
  748. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  749. var cache = this._valueCache[uniformName];
  750. if (!cache) {
  751. cache = [x, y, z];
  752. this._valueCache[uniformName] = cache;
  753. return true;
  754. }
  755. var changed = false;
  756. if (cache[0] !== x) {
  757. cache[0] = x;
  758. changed = true;
  759. }
  760. if (cache[1] !== y) {
  761. cache[1] = y;
  762. changed = true;
  763. }
  764. if (cache[2] !== z) {
  765. cache[2] = z;
  766. changed = true;
  767. }
  768. return changed;
  769. };
  770. /** @ignore */
  771. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  772. var cache = this._valueCache[uniformName];
  773. if (!cache) {
  774. cache = [x, y, z, w];
  775. this._valueCache[uniformName] = cache;
  776. return true;
  777. }
  778. var changed = false;
  779. if (cache[0] !== x) {
  780. cache[0] = x;
  781. changed = true;
  782. }
  783. if (cache[1] !== y) {
  784. cache[1] = y;
  785. changed = true;
  786. }
  787. if (cache[2] !== z) {
  788. cache[2] = z;
  789. changed = true;
  790. }
  791. if (cache[3] !== w) {
  792. cache[3] = w;
  793. changed = true;
  794. }
  795. return changed;
  796. };
  797. /**
  798. * Binds a buffer to a uniform.
  799. * @param buffer Buffer to bind.
  800. * @param name Name of the uniform variable to bind to.
  801. */
  802. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  803. var bufferName = this._uniformBuffersNames[name];
  804. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  805. return;
  806. }
  807. Effect._baseCache[bufferName] = buffer;
  808. this._engine.bindUniformBufferBase(buffer, bufferName);
  809. };
  810. /**
  811. * Binds block to a uniform.
  812. * @param blockName Name of the block to bind.
  813. * @param index Index to bind.
  814. */
  815. Effect.prototype.bindUniformBlock = function (blockName, index) {
  816. this._engine.bindUniformBlock(this._program, blockName, index);
  817. };
  818. /**
  819. * Sets an interger value on a uniform variable.
  820. * @param uniformName Name of the variable.
  821. * @param value Value to be set.
  822. * @returns this effect.
  823. */
  824. Effect.prototype.setInt = function (uniformName, value) {
  825. var cache = this._valueCache[uniformName];
  826. if (cache !== undefined && cache === value)
  827. return this;
  828. this._valueCache[uniformName] = value;
  829. this._engine.setInt(this.getUniform(uniformName), value);
  830. return this;
  831. };
  832. /**
  833. * Sets an int array on a uniform variable.
  834. * @param uniformName Name of the variable.
  835. * @param array array to be set.
  836. * @returns this effect.
  837. */
  838. Effect.prototype.setIntArray = function (uniformName, array) {
  839. this._valueCache[uniformName] = null;
  840. this._engine.setIntArray(this.getUniform(uniformName), array);
  841. return this;
  842. };
  843. /**
  844. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  845. * @param uniformName Name of the variable.
  846. * @param array array to be set.
  847. * @returns this effect.
  848. */
  849. Effect.prototype.setIntArray2 = function (uniformName, array) {
  850. this._valueCache[uniformName] = null;
  851. this._engine.setIntArray2(this.getUniform(uniformName), array);
  852. return this;
  853. };
  854. /**
  855. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  856. * @param uniformName Name of the variable.
  857. * @param array array to be set.
  858. * @returns this effect.
  859. */
  860. Effect.prototype.setIntArray3 = function (uniformName, array) {
  861. this._valueCache[uniformName] = null;
  862. this._engine.setIntArray3(this.getUniform(uniformName), array);
  863. return this;
  864. };
  865. /**
  866. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  867. * @param uniformName Name of the variable.
  868. * @param array array to be set.
  869. * @returns this effect.
  870. */
  871. Effect.prototype.setIntArray4 = function (uniformName, array) {
  872. this._valueCache[uniformName] = null;
  873. this._engine.setIntArray4(this.getUniform(uniformName), array);
  874. return this;
  875. };
  876. /**
  877. * Sets an float array on a uniform variable.
  878. * @param uniformName Name of the variable.
  879. * @param array array to be set.
  880. * @returns this effect.
  881. */
  882. Effect.prototype.setFloatArray = function (uniformName, array) {
  883. this._valueCache[uniformName] = null;
  884. this._engine.setFloatArray(this.getUniform(uniformName), array);
  885. return this;
  886. };
  887. /**
  888. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  889. * @param uniformName Name of the variable.
  890. * @param array array to be set.
  891. * @returns this effect.
  892. */
  893. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  894. this._valueCache[uniformName] = null;
  895. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  896. return this;
  897. };
  898. /**
  899. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  900. * @param uniformName Name of the variable.
  901. * @param array array to be set.
  902. * @returns this effect.
  903. */
  904. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  905. this._valueCache[uniformName] = null;
  906. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  907. return this;
  908. };
  909. /**
  910. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  911. * @param uniformName Name of the variable.
  912. * @param array array to be set.
  913. * @returns this effect.
  914. */
  915. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  916. this._valueCache[uniformName] = null;
  917. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  918. return this;
  919. };
  920. /**
  921. * Sets an array on a uniform variable.
  922. * @param uniformName Name of the variable.
  923. * @param array array to be set.
  924. * @returns this effect.
  925. */
  926. Effect.prototype.setArray = function (uniformName, array) {
  927. this._valueCache[uniformName] = null;
  928. this._engine.setArray(this.getUniform(uniformName), array);
  929. return this;
  930. };
  931. /**
  932. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  933. * @param uniformName Name of the variable.
  934. * @param array array to be set.
  935. * @returns this effect.
  936. */
  937. Effect.prototype.setArray2 = function (uniformName, array) {
  938. this._valueCache[uniformName] = null;
  939. this._engine.setArray2(this.getUniform(uniformName), array);
  940. return this;
  941. };
  942. /**
  943. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  944. * @param uniformName Name of the variable.
  945. * @param array array to be set.
  946. * @returns this effect.
  947. */
  948. Effect.prototype.setArray3 = function (uniformName, array) {
  949. this._valueCache[uniformName] = null;
  950. this._engine.setArray3(this.getUniform(uniformName), array);
  951. return this;
  952. };
  953. /**
  954. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  955. * @param uniformName Name of the variable.
  956. * @param array array to be set.
  957. * @returns this effect.
  958. */
  959. Effect.prototype.setArray4 = function (uniformName, array) {
  960. this._valueCache[uniformName] = null;
  961. this._engine.setArray4(this.getUniform(uniformName), array);
  962. return this;
  963. };
  964. /**
  965. * Sets matrices on a uniform variable.
  966. * @param uniformName Name of the variable.
  967. * @param matrices matrices to be set.
  968. * @returns this effect.
  969. */
  970. Effect.prototype.setMatrices = function (uniformName, matrices) {
  971. if (!matrices) {
  972. return this;
  973. }
  974. this._valueCache[uniformName] = null;
  975. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  976. return this;
  977. };
  978. /**
  979. * Sets matrix on a uniform variable.
  980. * @param uniformName Name of the variable.
  981. * @param matrix matrix to be set.
  982. * @returns this effect.
  983. */
  984. Effect.prototype.setMatrix = function (uniformName, matrix) {
  985. if (this._cacheMatrix(uniformName, matrix)) {
  986. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  987. }
  988. return this;
  989. };
  990. /**
  991. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  992. * @param uniformName Name of the variable.
  993. * @param matrix matrix to be set.
  994. * @returns this effect.
  995. */
  996. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  997. this._valueCache[uniformName] = null;
  998. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  999. return this;
  1000. };
  1001. /**
  1002. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1003. * @param uniformName Name of the variable.
  1004. * @param matrix matrix to be set.
  1005. * @returns this effect.
  1006. */
  1007. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1008. this._valueCache[uniformName] = null;
  1009. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1010. return this;
  1011. };
  1012. /**
  1013. * Sets a float on a uniform variable.
  1014. * @param uniformName Name of the variable.
  1015. * @param value value to be set.
  1016. * @returns this effect.
  1017. */
  1018. Effect.prototype.setFloat = function (uniformName, value) {
  1019. var cache = this._valueCache[uniformName];
  1020. if (cache !== undefined && cache === value)
  1021. return this;
  1022. this._valueCache[uniformName] = value;
  1023. this._engine.setFloat(this.getUniform(uniformName), value);
  1024. return this;
  1025. };
  1026. /**
  1027. * Sets a boolean on a uniform variable.
  1028. * @param uniformName Name of the variable.
  1029. * @param bool value to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setBool = function (uniformName, bool) {
  1033. var cache = this._valueCache[uniformName];
  1034. if (cache !== undefined && cache === bool)
  1035. return this;
  1036. this._valueCache[uniformName] = bool;
  1037. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1038. return this;
  1039. };
  1040. /**
  1041. * Sets a Vector2 on a uniform variable.
  1042. * @param uniformName Name of the variable.
  1043. * @param vector2 vector2 to be set.
  1044. * @returns this effect.
  1045. */
  1046. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1047. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1048. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1049. }
  1050. return this;
  1051. };
  1052. /**
  1053. * Sets a float2 on a uniform variable.
  1054. * @param uniformName Name of the variable.
  1055. * @param x First float in float2.
  1056. * @param y Second float in float2.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1060. if (this._cacheFloat2(uniformName, x, y)) {
  1061. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1062. }
  1063. return this;
  1064. };
  1065. /**
  1066. * Sets a Vector3 on a uniform variable.
  1067. * @param uniformName Name of the variable.
  1068. * @param vector3 Value to be set.
  1069. * @returns this effect.
  1070. */
  1071. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1072. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1073. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1074. }
  1075. return this;
  1076. };
  1077. /**
  1078. * Sets a float3 on a uniform variable.
  1079. * @param uniformName Name of the variable.
  1080. * @param x First float in float3.
  1081. * @param y Second float in float3.
  1082. * @param z Third float in float3.
  1083. * @returns this effect.
  1084. */
  1085. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1086. if (this._cacheFloat3(uniformName, x, y, z)) {
  1087. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1088. }
  1089. return this;
  1090. };
  1091. /**
  1092. * Sets a Vector4 on a uniform variable.
  1093. * @param uniformName Name of the variable.
  1094. * @param vector4 Value to be set.
  1095. * @returns this effect.
  1096. */
  1097. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1098. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1099. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1100. }
  1101. return this;
  1102. };
  1103. /**
  1104. * Sets a float4 on a uniform variable.
  1105. * @param uniformName Name of the variable.
  1106. * @param x First float in float4.
  1107. * @param y Second float in float4.
  1108. * @param z Third float in float4.
  1109. * @param w Fourth float in float4.
  1110. * @returns this effect.
  1111. */
  1112. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1113. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1114. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1115. }
  1116. return this;
  1117. };
  1118. /**
  1119. * Sets a Color3 on a uniform variable.
  1120. * @param uniformName Name of the variable.
  1121. * @param color3 Value to be set.
  1122. * @returns this effect.
  1123. */
  1124. Effect.prototype.setColor3 = function (uniformName, color3) {
  1125. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1126. this._engine.setColor3(this.getUniform(uniformName), color3);
  1127. }
  1128. return this;
  1129. };
  1130. /**
  1131. * Sets a Color4 on a uniform variable.
  1132. * @param uniformName Name of the variable.
  1133. * @param color3 Value to be set.
  1134. * @param alpha Alpha value to be set.
  1135. * @returns this effect.
  1136. */
  1137. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1138. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1139. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1140. }
  1141. return this;
  1142. };
  1143. /**
  1144. * Resets the cache of effects.
  1145. */
  1146. Effect.ResetCache = function () {
  1147. Effect._baseCache = {};
  1148. };
  1149. Effect._uniqueIdSeed = 0;
  1150. Effect._baseCache = {};
  1151. // Statics
  1152. /**
  1153. * Store of each shader (The can be looked up using effect.key)
  1154. */
  1155. Effect.ShadersStore = {};
  1156. /**
  1157. * Store of each included file for a shader (The can be looked up using effect.key)
  1158. */
  1159. Effect.IncludesShadersStore = {};
  1160. return Effect;
  1161. }());
  1162. BABYLON.Effect = Effect;
  1163. })(BABYLON || (BABYLON = {}));
  1164. //# sourceMappingURL=babylon.effect.js.map
  1165. //# sourceMappingURL=babylon.types.js.map
  1166. var BABYLON;
  1167. (function (BABYLON) {
  1168. var KeyboardEventTypes = /** @class */ (function () {
  1169. function KeyboardEventTypes() {
  1170. }
  1171. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1172. get: function () {
  1173. return KeyboardEventTypes._KEYDOWN;
  1174. },
  1175. enumerable: true,
  1176. configurable: true
  1177. });
  1178. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1179. get: function () {
  1180. return KeyboardEventTypes._KEYUP;
  1181. },
  1182. enumerable: true,
  1183. configurable: true
  1184. });
  1185. KeyboardEventTypes._KEYDOWN = 0x01;
  1186. KeyboardEventTypes._KEYUP = 0x02;
  1187. return KeyboardEventTypes;
  1188. }());
  1189. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1190. var KeyboardInfo = /** @class */ (function () {
  1191. function KeyboardInfo(type, event) {
  1192. this.type = type;
  1193. this.event = event;
  1194. }
  1195. return KeyboardInfo;
  1196. }());
  1197. BABYLON.KeyboardInfo = KeyboardInfo;
  1198. /**
  1199. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1200. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1201. */
  1202. var KeyboardInfoPre = /** @class */ (function (_super) {
  1203. __extends(KeyboardInfoPre, _super);
  1204. function KeyboardInfoPre(type, event) {
  1205. var _this = _super.call(this, type, event) || this;
  1206. _this.skipOnPointerObservable = false;
  1207. return _this;
  1208. }
  1209. return KeyboardInfoPre;
  1210. }(KeyboardInfo));
  1211. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1212. })(BABYLON || (BABYLON = {}));
  1213. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1214. var BABYLON;
  1215. (function (BABYLON) {
  1216. var PointerEventTypes = /** @class */ (function () {
  1217. function PointerEventTypes() {
  1218. }
  1219. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1220. get: function () {
  1221. return PointerEventTypes._POINTERDOWN;
  1222. },
  1223. enumerable: true,
  1224. configurable: true
  1225. });
  1226. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1227. get: function () {
  1228. return PointerEventTypes._POINTERUP;
  1229. },
  1230. enumerable: true,
  1231. configurable: true
  1232. });
  1233. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1234. get: function () {
  1235. return PointerEventTypes._POINTERMOVE;
  1236. },
  1237. enumerable: true,
  1238. configurable: true
  1239. });
  1240. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1241. get: function () {
  1242. return PointerEventTypes._POINTERWHEEL;
  1243. },
  1244. enumerable: true,
  1245. configurable: true
  1246. });
  1247. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1248. get: function () {
  1249. return PointerEventTypes._POINTERPICK;
  1250. },
  1251. enumerable: true,
  1252. configurable: true
  1253. });
  1254. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1255. get: function () {
  1256. return PointerEventTypes._POINTERTAP;
  1257. },
  1258. enumerable: true,
  1259. configurable: true
  1260. });
  1261. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1262. get: function () {
  1263. return PointerEventTypes._POINTERDOUBLETAP;
  1264. },
  1265. enumerable: true,
  1266. configurable: true
  1267. });
  1268. PointerEventTypes._POINTERDOWN = 0x01;
  1269. PointerEventTypes._POINTERUP = 0x02;
  1270. PointerEventTypes._POINTERMOVE = 0x04;
  1271. PointerEventTypes._POINTERWHEEL = 0x08;
  1272. PointerEventTypes._POINTERPICK = 0x10;
  1273. PointerEventTypes._POINTERTAP = 0x20;
  1274. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1275. return PointerEventTypes;
  1276. }());
  1277. BABYLON.PointerEventTypes = PointerEventTypes;
  1278. var PointerInfoBase = /** @class */ (function () {
  1279. function PointerInfoBase(type, event) {
  1280. this.type = type;
  1281. this.event = event;
  1282. }
  1283. return PointerInfoBase;
  1284. }());
  1285. BABYLON.PointerInfoBase = PointerInfoBase;
  1286. /**
  1287. * This class is used to store pointer related info for the onPrePointerObservable event.
  1288. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1289. */
  1290. var PointerInfoPre = /** @class */ (function (_super) {
  1291. __extends(PointerInfoPre, _super);
  1292. function PointerInfoPre(type, event, localX, localY) {
  1293. var _this = _super.call(this, type, event) || this;
  1294. _this.skipOnPointerObservable = false;
  1295. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1296. return _this;
  1297. }
  1298. return PointerInfoPre;
  1299. }(PointerInfoBase));
  1300. BABYLON.PointerInfoPre = PointerInfoPre;
  1301. /**
  1302. * This type contains all the data related to a pointer event in Babylon.js.
  1303. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1304. */
  1305. var PointerInfo = /** @class */ (function (_super) {
  1306. __extends(PointerInfo, _super);
  1307. function PointerInfo(type, event, pickInfo) {
  1308. var _this = _super.call(this, type, event) || this;
  1309. _this.pickInfo = pickInfo;
  1310. return _this;
  1311. }
  1312. return PointerInfo;
  1313. }(PointerInfoBase));
  1314. BABYLON.PointerInfo = PointerInfo;
  1315. })(BABYLON || (BABYLON = {}));
  1316. //# sourceMappingURL=babylon.pointerEvents.js.map
  1317. var BABYLON;
  1318. (function (BABYLON) {
  1319. BABYLON.ToGammaSpace = 1 / 2.2;
  1320. BABYLON.ToLinearSpace = 2.2;
  1321. BABYLON.Epsilon = 0.001;
  1322. /**
  1323. * Class used to hold a RBG color
  1324. */
  1325. var Color3 = /** @class */ (function () {
  1326. /**
  1327. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1328. * @param r defines the red component (between 0 and 1, default is 0)
  1329. * @param g defines the green component (between 0 and 1, default is 0)
  1330. * @param b defines the blue component (between 0 and 1, default is 0)
  1331. */
  1332. function Color3(
  1333. /**
  1334. * Defines the red component (between 0 and 1, default is 0)
  1335. */
  1336. r,
  1337. /**
  1338. * Defines the green component (between 0 and 1, default is 0)
  1339. */
  1340. g,
  1341. /**
  1342. * Defines the blue component (between 0 and 1, default is 0)
  1343. */
  1344. b) {
  1345. if (r === void 0) { r = 0; }
  1346. if (g === void 0) { g = 0; }
  1347. if (b === void 0) { b = 0; }
  1348. this.r = r;
  1349. this.g = g;
  1350. this.b = b;
  1351. }
  1352. /**
  1353. * Creates a string with the Color3 current values
  1354. * @returns the string representation of the Color3 object
  1355. */
  1356. Color3.prototype.toString = function () {
  1357. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1358. };
  1359. /**
  1360. * Returns the string "Color3"
  1361. * @returns "Color3"
  1362. */
  1363. Color3.prototype.getClassName = function () {
  1364. return "Color3";
  1365. };
  1366. /**
  1367. * Compute the Color3 hash code
  1368. * @returns an unique number that can be used to hash Color3 objects
  1369. */
  1370. Color3.prototype.getHashCode = function () {
  1371. var hash = this.r || 0;
  1372. hash = (hash * 397) ^ (this.g || 0);
  1373. hash = (hash * 397) ^ (this.b || 0);
  1374. return hash;
  1375. };
  1376. // Operators
  1377. /**
  1378. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1379. * @param array defines the array where to store the r,g,b components
  1380. * @param index defines an optional index in the target array to define where to start storing values
  1381. * @returns the current Color3 object
  1382. */
  1383. Color3.prototype.toArray = function (array, index) {
  1384. if (index === undefined) {
  1385. index = 0;
  1386. }
  1387. array[index] = this.r;
  1388. array[index + 1] = this.g;
  1389. array[index + 2] = this.b;
  1390. return this;
  1391. };
  1392. /**
  1393. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1394. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1395. * @returns a new {BABYLON.Color4} object
  1396. */
  1397. Color3.prototype.toColor4 = function (alpha) {
  1398. if (alpha === void 0) { alpha = 1; }
  1399. return new Color4(this.r, this.g, this.b, alpha);
  1400. };
  1401. /**
  1402. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1403. * @returns the new array
  1404. */
  1405. Color3.prototype.asArray = function () {
  1406. var result = new Array();
  1407. this.toArray(result, 0);
  1408. return result;
  1409. };
  1410. /**
  1411. * Returns the luminance value
  1412. * @returns a float value
  1413. */
  1414. Color3.prototype.toLuminance = function () {
  1415. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1416. };
  1417. /**
  1418. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1419. * @param otherColor defines the second operand
  1420. * @returns the new Color3 object
  1421. */
  1422. Color3.prototype.multiply = function (otherColor) {
  1423. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1424. };
  1425. /**
  1426. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1427. * @param otherColor defines the second operand
  1428. * @param result defines the Color3 object where to store the result
  1429. * @returns the current Color3
  1430. */
  1431. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1432. result.r = this.r * otherColor.r;
  1433. result.g = this.g * otherColor.g;
  1434. result.b = this.b * otherColor.b;
  1435. return this;
  1436. };
  1437. /**
  1438. * Determines equality between Color3 objects
  1439. * @param otherColor defines the second operand
  1440. * @returns true if the rgb values are equal to the passed ones
  1441. */
  1442. Color3.prototype.equals = function (otherColor) {
  1443. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1444. };
  1445. /**
  1446. * Determines equality between the current Color3 object and a set of r,b,g values
  1447. * @param r defines the red component to check
  1448. * @param g defines the green component to check
  1449. * @param b defines the blue component to check
  1450. * @returns true if the rgb values are equal to the passed ones
  1451. */
  1452. Color3.prototype.equalsFloats = function (r, g, b) {
  1453. return this.r === r && this.g === g && this.b === b;
  1454. };
  1455. /**
  1456. * Multiplies in place each rgb value by scale
  1457. * @param scale defines the scaling factor
  1458. * @returns the updated Color3.
  1459. */
  1460. Color3.prototype.scale = function (scale) {
  1461. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1462. };
  1463. /**
  1464. * Multiplies the rgb values by scale and stores the result into "result"
  1465. * @param scale defines the scaling factor
  1466. * @param result defines the Color3 object where to store the result
  1467. * @returns the unmodified current Color3.
  1468. */
  1469. Color3.prototype.scaleToRef = function (scale, result) {
  1470. result.r = this.r * scale;
  1471. result.g = this.g * scale;
  1472. result.b = this.b * scale;
  1473. return this;
  1474. };
  1475. /**
  1476. * Clamps the rgb values by the min and max values and stores the result into "result"
  1477. * @param min defines minimum clamping value (default is 0)
  1478. * @param max defines maximum clamping value (default is 1)
  1479. * @param result defines color to store the result into
  1480. * @returns the original Color3
  1481. */
  1482. Color3.prototype.clampToRef = function (min, max, result) {
  1483. if (min === void 0) { min = 0; }
  1484. if (max === void 0) { max = 1; }
  1485. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1486. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1487. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1488. return this;
  1489. };
  1490. /**
  1491. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1492. * @param otherColor defines the second operand
  1493. * @returns the new Color3
  1494. */
  1495. Color3.prototype.add = function (otherColor) {
  1496. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1497. };
  1498. /**
  1499. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1500. * @param otherColor defines the second operand
  1501. * @param result defines Color3 object to store the result into
  1502. * @returns the unmodified current Color3
  1503. */
  1504. Color3.prototype.addToRef = function (otherColor, result) {
  1505. result.r = this.r + otherColor.r;
  1506. result.g = this.g + otherColor.g;
  1507. result.b = this.b + otherColor.b;
  1508. return this;
  1509. };
  1510. /**
  1511. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1512. * @param otherColor defines the second operand
  1513. * @returns the new Color3
  1514. */
  1515. Color3.prototype.subtract = function (otherColor) {
  1516. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1517. };
  1518. /**
  1519. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1520. * @param otherColor defines the second operand
  1521. * @param result defines Color3 object to store the result into
  1522. * @returns the unmodified current Color3
  1523. */
  1524. Color3.prototype.subtractToRef = function (otherColor, result) {
  1525. result.r = this.r - otherColor.r;
  1526. result.g = this.g - otherColor.g;
  1527. result.b = this.b - otherColor.b;
  1528. return this;
  1529. };
  1530. /**
  1531. * Copy the current object
  1532. * @returns a new Color3 copied the current one
  1533. */
  1534. Color3.prototype.clone = function () {
  1535. return new Color3(this.r, this.g, this.b);
  1536. };
  1537. /**
  1538. * Copies the rgb values from the source in the current Color3
  1539. * @param source defines the source Color3 object
  1540. * @returns the updated Color3 object
  1541. */
  1542. Color3.prototype.copyFrom = function (source) {
  1543. this.r = source.r;
  1544. this.g = source.g;
  1545. this.b = source.b;
  1546. return this;
  1547. };
  1548. /**
  1549. * Updates the Color3 rgb values from the passed floats
  1550. * @param r defines the red component to read from
  1551. * @param g defines the green component to read from
  1552. * @param b defines the blue component to read from
  1553. * @returns the current Color3 object
  1554. */
  1555. Color3.prototype.copyFromFloats = function (r, g, b) {
  1556. this.r = r;
  1557. this.g = g;
  1558. this.b = b;
  1559. return this;
  1560. };
  1561. /**
  1562. * Updates the Color3 rgb values from the passed floats
  1563. * @param r defines the red component to read from
  1564. * @param g defines the green component to read from
  1565. * @param b defines the blue component to read from
  1566. * @returns the current Color3 object
  1567. */
  1568. Color3.prototype.set = function (r, g, b) {
  1569. return this.copyFromFloats(r, g, b);
  1570. };
  1571. /**
  1572. * Compute the Color3 hexadecimal code as a string
  1573. * @returns a string containing the hexadecimal representation of the Color3 object
  1574. */
  1575. Color3.prototype.toHexString = function () {
  1576. var intR = (this.r * 255) | 0;
  1577. var intG = (this.g * 255) | 0;
  1578. var intB = (this.b * 255) | 0;
  1579. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1580. };
  1581. /**
  1582. * Computes a new Color3 converted from the current one to linear space
  1583. * @returns a new Color3 object
  1584. */
  1585. Color3.prototype.toLinearSpace = function () {
  1586. var convertedColor = new Color3();
  1587. this.toLinearSpaceToRef(convertedColor);
  1588. return convertedColor;
  1589. };
  1590. /**
  1591. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1592. * @param convertedColor defines the Color3 object where to store the linear space version
  1593. * @returns the unmodified Color3
  1594. */
  1595. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1596. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1597. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1598. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1599. return this;
  1600. };
  1601. /**
  1602. * Computes a new Color3 converted from the current one to gamma space
  1603. * @returns a new Color3 object
  1604. */
  1605. Color3.prototype.toGammaSpace = function () {
  1606. var convertedColor = new Color3();
  1607. this.toGammaSpaceToRef(convertedColor);
  1608. return convertedColor;
  1609. };
  1610. /**
  1611. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1612. * @param convertedColor defines the Color3 object where to store the gamma space version
  1613. * @returns the unmodified Color3
  1614. */
  1615. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1616. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1617. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1618. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1619. return this;
  1620. };
  1621. // Statics
  1622. /**
  1623. * Creates a new Color3 from the string containing valid hexadecimal values
  1624. * @param hex defines a string containing valid hexadecimal values
  1625. * @returns a new Color3 object
  1626. */
  1627. Color3.FromHexString = function (hex) {
  1628. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1629. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1630. return new Color3(0, 0, 0);
  1631. }
  1632. var r = parseInt(hex.substring(1, 3), 16);
  1633. var g = parseInt(hex.substring(3, 5), 16);
  1634. var b = parseInt(hex.substring(5, 7), 16);
  1635. return Color3.FromInts(r, g, b);
  1636. };
  1637. /**
  1638. * Creates a new Vector3 from the starting index of the passed array
  1639. * @param array defines the source array
  1640. * @param offset defines an offset in the source array
  1641. * @returns a new Color3 object
  1642. */
  1643. Color3.FromArray = function (array, offset) {
  1644. if (offset === void 0) { offset = 0; }
  1645. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1646. };
  1647. /**
  1648. * Creates a new Color3 from integer values (< 256)
  1649. * @param r defines the red component to read from (value between 0 and 255)
  1650. * @param g defines the green component to read from (value between 0 and 255)
  1651. * @param b defines the blue component to read from (value between 0 and 255)
  1652. * @returns a new Color3 object
  1653. */
  1654. Color3.FromInts = function (r, g, b) {
  1655. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1656. };
  1657. /**
  1658. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1659. * @param start defines the start Color3 value
  1660. * @param end defines the end Color3 value
  1661. * @param amount defines the gradient value between start and end
  1662. * @returns a new Color3 object
  1663. */
  1664. Color3.Lerp = function (start, end, amount) {
  1665. var r = start.r + ((end.r - start.r) * amount);
  1666. var g = start.g + ((end.g - start.g) * amount);
  1667. var b = start.b + ((end.b - start.b) * amount);
  1668. return new Color3(r, g, b);
  1669. };
  1670. /**
  1671. * Returns a Color3 value containing a red color
  1672. * @returns a new Color3 object
  1673. */
  1674. Color3.Red = function () { return new Color3(1, 0, 0); };
  1675. /**
  1676. * Returns a Color3 value containing a green color
  1677. * @returns a new Color3 object
  1678. */
  1679. Color3.Green = function () { return new Color3(0, 1, 0); };
  1680. /**
  1681. * Returns a Color3 value containing a blue color
  1682. * @returns a new Color3 object
  1683. */
  1684. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1685. /**
  1686. * Returns a Color3 value containing a black color
  1687. * @returns a new Color3 object
  1688. */
  1689. Color3.Black = function () { return new Color3(0, 0, 0); };
  1690. /**
  1691. * Returns a Color3 value containing a white color
  1692. * @returns a new Color3 object
  1693. */
  1694. Color3.White = function () { return new Color3(1, 1, 1); };
  1695. /**
  1696. * Returns a Color3 value containing a purple color
  1697. * @returns a new Color3 object
  1698. */
  1699. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1700. /**
  1701. * Returns a Color3 value containing a magenta color
  1702. * @returns a new Color3 object
  1703. */
  1704. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1705. /**
  1706. * Returns a Color3 value containing a yellow color
  1707. * @returns a new Color3 object
  1708. */
  1709. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1710. /**
  1711. * Returns a Color3 value containing a gray color
  1712. * @returns a new Color3 object
  1713. */
  1714. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1715. /**
  1716. * Returns a Color3 value containing a teal color
  1717. * @returns a new Color3 object
  1718. */
  1719. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1720. /**
  1721. * Returns a Color3 value containing a random color
  1722. * @returns a new Color3 object
  1723. */
  1724. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1725. return Color3;
  1726. }());
  1727. BABYLON.Color3 = Color3;
  1728. /**
  1729. * Class used to hold a RBGA color
  1730. */
  1731. var Color4 = /** @class */ (function () {
  1732. /**
  1733. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1734. * @param r defines the red component (between 0 and 1, default is 0)
  1735. * @param g defines the green component (between 0 and 1, default is 0)
  1736. * @param b defines the blue component (between 0 and 1, default is 0)
  1737. * @param a defines the alpha component (between 0 and 1, default is 1)
  1738. */
  1739. function Color4(
  1740. /**
  1741. * Defines the red component (between 0 and 1, default is 0)
  1742. */
  1743. r,
  1744. /**
  1745. * Defines the green component (between 0 and 1, default is 0)
  1746. */
  1747. g,
  1748. /**
  1749. * Defines the blue component (between 0 and 1, default is 0)
  1750. */
  1751. b,
  1752. /**
  1753. * Defines the alpha component (between 0 and 1, default is 1)
  1754. */
  1755. a) {
  1756. if (r === void 0) { r = 0; }
  1757. if (g === void 0) { g = 0; }
  1758. if (b === void 0) { b = 0; }
  1759. if (a === void 0) { a = 1; }
  1760. this.r = r;
  1761. this.g = g;
  1762. this.b = b;
  1763. this.a = a;
  1764. }
  1765. // Operators
  1766. /**
  1767. * Adds in place the passed Color4 values to the current Color4 object
  1768. * @param right defines the second operand
  1769. * @returns the current updated Color4 object
  1770. */
  1771. Color4.prototype.addInPlace = function (right) {
  1772. this.r += right.r;
  1773. this.g += right.g;
  1774. this.b += right.b;
  1775. this.a += right.a;
  1776. return this;
  1777. };
  1778. /**
  1779. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1780. * @returns the new array
  1781. */
  1782. Color4.prototype.asArray = function () {
  1783. var result = new Array();
  1784. this.toArray(result, 0);
  1785. return result;
  1786. };
  1787. /**
  1788. * Stores from the starting index in the passed array the Color4 successive values
  1789. * @param array defines the array where to store the r,g,b components
  1790. * @param index defines an optional index in the target array to define where to start storing values
  1791. * @returns the current Color4 object
  1792. */
  1793. Color4.prototype.toArray = function (array, index) {
  1794. if (index === undefined) {
  1795. index = 0;
  1796. }
  1797. array[index] = this.r;
  1798. array[index + 1] = this.g;
  1799. array[index + 2] = this.b;
  1800. array[index + 3] = this.a;
  1801. return this;
  1802. };
  1803. /**
  1804. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1805. * @param right defines the second operand
  1806. * @returns a new Color4 object
  1807. */
  1808. Color4.prototype.add = function (right) {
  1809. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1810. };
  1811. /**
  1812. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1813. * @param right defines the second operand
  1814. * @returns a new Color4 object
  1815. */
  1816. Color4.prototype.subtract = function (right) {
  1817. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1818. };
  1819. /**
  1820. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1821. * @param right defines the second operand
  1822. * @param result defines the Color4 object where to store the result
  1823. * @returns the current Color4 object
  1824. */
  1825. Color4.prototype.subtractToRef = function (right, result) {
  1826. result.r = this.r - right.r;
  1827. result.g = this.g - right.g;
  1828. result.b = this.b - right.b;
  1829. result.a = this.a - right.a;
  1830. return this;
  1831. };
  1832. /**
  1833. * Creates a new Color4 with the current Color4 values multiplied by scale
  1834. * @param scale defines the scaling factor to apply
  1835. * @returns a new Color4 object
  1836. */
  1837. Color4.prototype.scale = function (scale) {
  1838. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1839. };
  1840. /**
  1841. * Multiplies the current Color4 values by scale and stores the result in "result"
  1842. * @param scale defines the scaling factor to apply
  1843. * @param result defines the Color4 object where to store the result
  1844. * @returns the current Color4.
  1845. */
  1846. Color4.prototype.scaleToRef = function (scale, result) {
  1847. result.r = this.r * scale;
  1848. result.g = this.g * scale;
  1849. result.b = this.b * scale;
  1850. result.a = this.a * scale;
  1851. return this;
  1852. };
  1853. /**
  1854. * Clamps the rgb values by the min and max values and stores the result into "result"
  1855. * @param min defines minimum clamping value (default is 0)
  1856. * @param max defines maximum clamping value (default is 1)
  1857. * @param result defines color to store the result into.
  1858. * @returns the cuurent Color4
  1859. */
  1860. Color4.prototype.clampToRef = function (min, max, result) {
  1861. if (min === void 0) { min = 0; }
  1862. if (max === void 0) { max = 1; }
  1863. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1864. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1865. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1866. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1867. return this;
  1868. };
  1869. /**
  1870. * Multipy an Color4 value by another and return a new Color4 object
  1871. * @param color defines the Color4 value to multiply by
  1872. * @returns a new Color4 object
  1873. */
  1874. Color4.prototype.multiply = function (color) {
  1875. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1876. };
  1877. /**
  1878. * Multipy a Color4 value by another and push the result in a reference value
  1879. * @param color defines the Color4 value to multiply by
  1880. * @param result defines the Color4 to fill the result in
  1881. * @returns the result Color4
  1882. */
  1883. Color4.prototype.multiplyToRef = function (color, result) {
  1884. result.r = this.r * color.r;
  1885. result.g = this.g * color.g;
  1886. result.b = this.b * color.b;
  1887. result.a = this.a * color.a;
  1888. return result;
  1889. };
  1890. /**
  1891. * Creates a string with the Color4 current values
  1892. * @returns the string representation of the Color4 object
  1893. */
  1894. Color4.prototype.toString = function () {
  1895. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1896. };
  1897. /**
  1898. * Returns the string "Color4"
  1899. * @returns "Color4"
  1900. */
  1901. Color4.prototype.getClassName = function () {
  1902. return "Color4";
  1903. };
  1904. /**
  1905. * Compute the Color4 hash code
  1906. * @returns an unique number that can be used to hash Color4 objects
  1907. */
  1908. Color4.prototype.getHashCode = function () {
  1909. var hash = this.r || 0;
  1910. hash = (hash * 397) ^ (this.g || 0);
  1911. hash = (hash * 397) ^ (this.b || 0);
  1912. hash = (hash * 397) ^ (this.a || 0);
  1913. return hash;
  1914. };
  1915. /**
  1916. * Creates a new Color4 copied from the current one
  1917. * @returns a new Color4 object
  1918. */
  1919. Color4.prototype.clone = function () {
  1920. return new Color4(this.r, this.g, this.b, this.a);
  1921. };
  1922. /**
  1923. * Copies the passed Color4 values into the current one
  1924. * @param source defines the source Color4 object
  1925. * @returns the current updated Color4 object
  1926. */
  1927. Color4.prototype.copyFrom = function (source) {
  1928. this.r = source.r;
  1929. this.g = source.g;
  1930. this.b = source.b;
  1931. this.a = source.a;
  1932. return this;
  1933. };
  1934. /**
  1935. * Copies the passed float values into the current one
  1936. * @param r defines the red component to read from
  1937. * @param g defines the green component to read from
  1938. * @param b defines the blue component to read from
  1939. * @param a defines the alpha component to read from
  1940. * @returns the current updated Color4 object
  1941. */
  1942. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1943. this.r = r;
  1944. this.g = g;
  1945. this.b = b;
  1946. this.a = a;
  1947. return this;
  1948. };
  1949. /**
  1950. * Copies the passed float values into the current one
  1951. * @param r defines the red component to read from
  1952. * @param g defines the green component to read from
  1953. * @param b defines the blue component to read from
  1954. * @param a defines the alpha component to read from
  1955. * @returns the current updated Color4 object
  1956. */
  1957. Color4.prototype.set = function (r, g, b, a) {
  1958. return this.copyFromFloats(r, g, b, a);
  1959. };
  1960. /**
  1961. * Compute the Color4 hexadecimal code as a string
  1962. * @returns a string containing the hexadecimal representation of the Color4 object
  1963. */
  1964. Color4.prototype.toHexString = function () {
  1965. var intR = (this.r * 255) | 0;
  1966. var intG = (this.g * 255) | 0;
  1967. var intB = (this.b * 255) | 0;
  1968. var intA = (this.a * 255) | 0;
  1969. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1970. };
  1971. /**
  1972. * Computes a new Color4 converted from the current one to linear space
  1973. * @returns a new Color4 object
  1974. */
  1975. Color4.prototype.toLinearSpace = function () {
  1976. var convertedColor = new Color4();
  1977. this.toLinearSpaceToRef(convertedColor);
  1978. return convertedColor;
  1979. };
  1980. /**
  1981. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  1982. * @param convertedColor defines the Color4 object where to store the linear space version
  1983. * @returns the unmodified Color4
  1984. */
  1985. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  1986. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1987. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1988. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1989. convertedColor.a = this.a;
  1990. return this;
  1991. };
  1992. /**
  1993. * Computes a new Color4 converted from the current one to gamma space
  1994. * @returns a new Color4 object
  1995. */
  1996. Color4.prototype.toGammaSpace = function () {
  1997. var convertedColor = new Color4();
  1998. this.toGammaSpaceToRef(convertedColor);
  1999. return convertedColor;
  2000. };
  2001. /**
  2002. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2003. * @param convertedColor defines the Color4 object where to store the gamma space version
  2004. * @returns the unmodified Color4
  2005. */
  2006. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2007. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2008. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2009. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2010. convertedColor.a = this.a;
  2011. return this;
  2012. };
  2013. // Statics
  2014. /**
  2015. * Creates a new Color4 from the string containing valid hexadecimal values
  2016. * @param hex defines a string containing valid hexadecimal values
  2017. * @returns a new Color4 object
  2018. */
  2019. Color4.FromHexString = function (hex) {
  2020. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2021. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  2022. return new Color4(0.0, 0.0, 0.0, 0.0);
  2023. }
  2024. var r = parseInt(hex.substring(1, 3), 16);
  2025. var g = parseInt(hex.substring(3, 5), 16);
  2026. var b = parseInt(hex.substring(5, 7), 16);
  2027. var a = parseInt(hex.substring(7, 9), 16);
  2028. return Color4.FromInts(r, g, b, a);
  2029. };
  2030. /**
  2031. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2032. * @param left defines the start value
  2033. * @param right defines the end value
  2034. * @param amount defines the gradient factor
  2035. * @returns a new Color4 object
  2036. */
  2037. Color4.Lerp = function (left, right, amount) {
  2038. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2039. Color4.LerpToRef(left, right, amount, result);
  2040. return result;
  2041. };
  2042. /**
  2043. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2044. * @param left defines the start value
  2045. * @param right defines the end value
  2046. * @param amount defines the gradient factor
  2047. * @param result defines the Color4 object where to store data
  2048. */
  2049. Color4.LerpToRef = function (left, right, amount, result) {
  2050. result.r = left.r + (right.r - left.r) * amount;
  2051. result.g = left.g + (right.g - left.g) * amount;
  2052. result.b = left.b + (right.b - left.b) * amount;
  2053. result.a = left.a + (right.a - left.a) * amount;
  2054. };
  2055. /**
  2056. * Creates a new Color4 from the starting index element of the passed array
  2057. * @param array defines the source array to read from
  2058. * @param offset defines the offset in the source array
  2059. * @returns a new Color4 object
  2060. */
  2061. Color4.FromArray = function (array, offset) {
  2062. if (offset === void 0) { offset = 0; }
  2063. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2064. };
  2065. /**
  2066. * Creates a new Color3 from integer values (< 256)
  2067. * @param r defines the red component to read from (value between 0 and 255)
  2068. * @param g defines the green component to read from (value between 0 and 255)
  2069. * @param b defines the blue component to read from (value between 0 and 255)
  2070. * @param a defines the alpha component to read from (value between 0 and 255)
  2071. * @returns a new Color3 object
  2072. */
  2073. Color4.FromInts = function (r, g, b, a) {
  2074. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2075. };
  2076. /**
  2077. * Check the content of a given array and convert it to an array containing RGBA data
  2078. * If the original array was already containing count * 4 values then it is returned directly
  2079. * @param colors defines the array to check
  2080. * @param count defines the number of RGBA data to expect
  2081. * @returns an array containing count * 4 values (RGBA)
  2082. */
  2083. Color4.CheckColors4 = function (colors, count) {
  2084. // Check if color3 was used
  2085. if (colors.length === count * 3) {
  2086. var colors4 = [];
  2087. for (var index = 0; index < colors.length; index += 3) {
  2088. var newIndex = (index / 3) * 4;
  2089. colors4[newIndex] = colors[index];
  2090. colors4[newIndex + 1] = colors[index + 1];
  2091. colors4[newIndex + 2] = colors[index + 2];
  2092. colors4[newIndex + 3] = 1.0;
  2093. }
  2094. return colors4;
  2095. }
  2096. return colors;
  2097. };
  2098. return Color4;
  2099. }());
  2100. BABYLON.Color4 = Color4;
  2101. var Vector2 = /** @class */ (function () {
  2102. /**
  2103. * Creates a new Vector2 from the passed x and y coordinates.
  2104. */
  2105. function Vector2(x, y) {
  2106. this.x = x;
  2107. this.y = y;
  2108. }
  2109. /**
  2110. * Returns a string with the Vector2 coordinates.
  2111. */
  2112. Vector2.prototype.toString = function () {
  2113. return "{X: " + this.x + " Y:" + this.y + "}";
  2114. };
  2115. /**
  2116. * Returns the string "Vector2"
  2117. */
  2118. Vector2.prototype.getClassName = function () {
  2119. return "Vector2";
  2120. };
  2121. /**
  2122. * Returns the Vector2 hash code as a number.
  2123. */
  2124. Vector2.prototype.getHashCode = function () {
  2125. var hash = this.x || 0;
  2126. hash = (hash * 397) ^ (this.y || 0);
  2127. return hash;
  2128. };
  2129. // Operators
  2130. /**
  2131. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2132. * Returns the Vector2.
  2133. */
  2134. Vector2.prototype.toArray = function (array, index) {
  2135. if (index === void 0) { index = 0; }
  2136. array[index] = this.x;
  2137. array[index + 1] = this.y;
  2138. return this;
  2139. };
  2140. /**
  2141. * Returns a new array with 2 elements : the Vector2 coordinates.
  2142. */
  2143. Vector2.prototype.asArray = function () {
  2144. var result = new Array();
  2145. this.toArray(result, 0);
  2146. return result;
  2147. };
  2148. /**
  2149. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2150. * Returns the updated Vector2.
  2151. */
  2152. Vector2.prototype.copyFrom = function (source) {
  2153. this.x = source.x;
  2154. this.y = source.y;
  2155. return this;
  2156. };
  2157. /**
  2158. * Sets the Vector2 coordinates with the passed floats.
  2159. * Returns the updated Vector2.
  2160. */
  2161. Vector2.prototype.copyFromFloats = function (x, y) {
  2162. this.x = x;
  2163. this.y = y;
  2164. return this;
  2165. };
  2166. /**
  2167. * Sets the Vector2 coordinates with the passed floats.
  2168. * Returns the updated Vector2.
  2169. */
  2170. Vector2.prototype.set = function (x, y) {
  2171. return this.copyFromFloats(x, y);
  2172. };
  2173. /**
  2174. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2175. */
  2176. Vector2.prototype.add = function (otherVector) {
  2177. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2178. };
  2179. /**
  2180. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2181. * Returns the Vector2.
  2182. */
  2183. Vector2.prototype.addToRef = function (otherVector, result) {
  2184. result.x = this.x + otherVector.x;
  2185. result.y = this.y + otherVector.y;
  2186. return this;
  2187. };
  2188. /**
  2189. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2190. * Returns the updated Vector2.
  2191. */
  2192. Vector2.prototype.addInPlace = function (otherVector) {
  2193. this.x += otherVector.x;
  2194. this.y += otherVector.y;
  2195. return this;
  2196. };
  2197. /**
  2198. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2199. */
  2200. Vector2.prototype.addVector3 = function (otherVector) {
  2201. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2202. };
  2203. /**
  2204. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2205. */
  2206. Vector2.prototype.subtract = function (otherVector) {
  2207. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2208. };
  2209. /**
  2210. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2211. * Returns the Vector2.
  2212. */
  2213. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2214. result.x = this.x - otherVector.x;
  2215. result.y = this.y - otherVector.y;
  2216. return this;
  2217. };
  2218. /**
  2219. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2220. * Returns the updated Vector2.
  2221. */
  2222. Vector2.prototype.subtractInPlace = function (otherVector) {
  2223. this.x -= otherVector.x;
  2224. this.y -= otherVector.y;
  2225. return this;
  2226. };
  2227. /**
  2228. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2229. * Returns the updated Vector2.
  2230. */
  2231. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2232. this.x *= otherVector.x;
  2233. this.y *= otherVector.y;
  2234. return this;
  2235. };
  2236. /**
  2237. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2238. */
  2239. Vector2.prototype.multiply = function (otherVector) {
  2240. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2241. };
  2242. /**
  2243. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2244. * Returns the Vector2.
  2245. */
  2246. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2247. result.x = this.x * otherVector.x;
  2248. result.y = this.y * otherVector.y;
  2249. return this;
  2250. };
  2251. /**
  2252. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2253. */
  2254. Vector2.prototype.multiplyByFloats = function (x, y) {
  2255. return new Vector2(this.x * x, this.y * y);
  2256. };
  2257. /**
  2258. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2259. */
  2260. Vector2.prototype.divide = function (otherVector) {
  2261. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2262. };
  2263. /**
  2264. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2265. * Returns the Vector2.
  2266. */
  2267. Vector2.prototype.divideToRef = function (otherVector, result) {
  2268. result.x = this.x / otherVector.x;
  2269. result.y = this.y / otherVector.y;
  2270. return this;
  2271. };
  2272. /**
  2273. * Divides the current Vector3 coordinates by the passed ones.
  2274. * Returns the updated Vector3.
  2275. */
  2276. Vector2.prototype.divideInPlace = function (otherVector) {
  2277. return this.divideToRef(otherVector, this);
  2278. };
  2279. /**
  2280. * Returns a new Vector2 with current Vector2 negated coordinates.
  2281. */
  2282. Vector2.prototype.negate = function () {
  2283. return new Vector2(-this.x, -this.y);
  2284. };
  2285. /**
  2286. * Multiply the Vector2 coordinates by scale.
  2287. * Returns the updated Vector2.
  2288. */
  2289. Vector2.prototype.scaleInPlace = function (scale) {
  2290. this.x *= scale;
  2291. this.y *= scale;
  2292. return this;
  2293. };
  2294. /**
  2295. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2296. */
  2297. Vector2.prototype.scale = function (scale) {
  2298. return new Vector2(this.x * scale, this.y * scale);
  2299. };
  2300. /**
  2301. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2302. */
  2303. Vector2.prototype.equals = function (otherVector) {
  2304. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2305. };
  2306. /**
  2307. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2308. */
  2309. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2310. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2311. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2312. };
  2313. // Properties
  2314. /**
  2315. * Returns the vector length (float).
  2316. */
  2317. Vector2.prototype.length = function () {
  2318. return Math.sqrt(this.x * this.x + this.y * this.y);
  2319. };
  2320. /**
  2321. * Returns the vector squared length (float);
  2322. */
  2323. Vector2.prototype.lengthSquared = function () {
  2324. return (this.x * this.x + this.y * this.y);
  2325. };
  2326. // Methods
  2327. /**
  2328. * Normalize the vector.
  2329. * Returns the updated Vector2.
  2330. */
  2331. Vector2.prototype.normalize = function () {
  2332. var len = this.length();
  2333. if (len === 0)
  2334. return this;
  2335. var num = 1.0 / len;
  2336. this.x *= num;
  2337. this.y *= num;
  2338. return this;
  2339. };
  2340. /**
  2341. * Returns a new Vector2 copied from the Vector2.
  2342. */
  2343. Vector2.prototype.clone = function () {
  2344. return new Vector2(this.x, this.y);
  2345. };
  2346. // Statics
  2347. /**
  2348. * Returns a new Vector2(0, 0)
  2349. */
  2350. Vector2.Zero = function () {
  2351. return new Vector2(0, 0);
  2352. };
  2353. /**
  2354. * Returns a new Vector2(1, 1)
  2355. */
  2356. Vector2.One = function () {
  2357. return new Vector2(1, 1);
  2358. };
  2359. /**
  2360. * Returns a new Vector2 set from the passed index element of the passed array.
  2361. */
  2362. Vector2.FromArray = function (array, offset) {
  2363. if (offset === void 0) { offset = 0; }
  2364. return new Vector2(array[offset], array[offset + 1]);
  2365. };
  2366. /**
  2367. * Sets "result" from the passed index element of the passed array.
  2368. */
  2369. Vector2.FromArrayToRef = function (array, offset, result) {
  2370. result.x = array[offset];
  2371. result.y = array[offset + 1];
  2372. };
  2373. /**
  2374. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2375. */
  2376. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2377. var squared = amount * amount;
  2378. var cubed = amount * squared;
  2379. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2380. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2381. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2382. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2383. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2384. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2385. return new Vector2(x, y);
  2386. };
  2387. /**
  2388. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2389. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2390. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2391. */
  2392. Vector2.Clamp = function (value, min, max) {
  2393. var x = value.x;
  2394. x = (x > max.x) ? max.x : x;
  2395. x = (x < min.x) ? min.x : x;
  2396. var y = value.y;
  2397. y = (y > max.y) ? max.y : y;
  2398. y = (y < min.y) ? min.y : y;
  2399. return new Vector2(x, y);
  2400. };
  2401. /**
  2402. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2403. */
  2404. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2405. var squared = amount * amount;
  2406. var cubed = amount * squared;
  2407. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2408. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2409. var part3 = (cubed - (2.0 * squared)) + amount;
  2410. var part4 = cubed - squared;
  2411. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2412. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2413. return new Vector2(x, y);
  2414. };
  2415. /**
  2416. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2417. */
  2418. Vector2.Lerp = function (start, end, amount) {
  2419. var x = start.x + ((end.x - start.x) * amount);
  2420. var y = start.y + ((end.y - start.y) * amount);
  2421. return new Vector2(x, y);
  2422. };
  2423. /**
  2424. * Returns the dot product (float) of the vector "left" and the vector "right".
  2425. */
  2426. Vector2.Dot = function (left, right) {
  2427. return left.x * right.x + left.y * right.y;
  2428. };
  2429. /**
  2430. * Returns a new Vector2 equal to the normalized passed vector.
  2431. */
  2432. Vector2.Normalize = function (vector) {
  2433. var newVector = vector.clone();
  2434. newVector.normalize();
  2435. return newVector;
  2436. };
  2437. /**
  2438. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2439. */
  2440. Vector2.Minimize = function (left, right) {
  2441. var x = (left.x < right.x) ? left.x : right.x;
  2442. var y = (left.y < right.y) ? left.y : right.y;
  2443. return new Vector2(x, y);
  2444. };
  2445. /**
  2446. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2447. */
  2448. Vector2.Maximize = function (left, right) {
  2449. var x = (left.x > right.x) ? left.x : right.x;
  2450. var y = (left.y > right.y) ? left.y : right.y;
  2451. return new Vector2(x, y);
  2452. };
  2453. /**
  2454. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2455. */
  2456. Vector2.Transform = function (vector, transformation) {
  2457. var r = Vector2.Zero();
  2458. Vector2.TransformToRef(vector, transformation, r);
  2459. return r;
  2460. };
  2461. /**
  2462. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2463. */
  2464. Vector2.TransformToRef = function (vector, transformation, result) {
  2465. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2466. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2467. result.x = x;
  2468. result.y = y;
  2469. };
  2470. /**
  2471. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2472. */
  2473. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2474. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2475. var sign = a < 0 ? -1 : 1;
  2476. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2477. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2478. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2479. };
  2480. /**
  2481. * Returns the distance (float) between the vectors "value1" and "value2".
  2482. */
  2483. Vector2.Distance = function (value1, value2) {
  2484. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2485. };
  2486. /**
  2487. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2488. */
  2489. Vector2.DistanceSquared = function (value1, value2) {
  2490. var x = value1.x - value2.x;
  2491. var y = value1.y - value2.y;
  2492. return (x * x) + (y * y);
  2493. };
  2494. /**
  2495. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2496. */
  2497. Vector2.Center = function (value1, value2) {
  2498. var center = value1.add(value2);
  2499. center.scaleInPlace(0.5);
  2500. return center;
  2501. };
  2502. /**
  2503. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2504. */
  2505. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2506. var l2 = Vector2.DistanceSquared(segA, segB);
  2507. if (l2 === 0.0) {
  2508. return Vector2.Distance(p, segA);
  2509. }
  2510. var v = segB.subtract(segA);
  2511. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2512. var proj = segA.add(v.multiplyByFloats(t, t));
  2513. return Vector2.Distance(p, proj);
  2514. };
  2515. return Vector2;
  2516. }());
  2517. BABYLON.Vector2 = Vector2;
  2518. /**
  2519. * Classed used to store (x,y,z) vector representation
  2520. * A Vector3 is the main object used in 3D geometry
  2521. * It can represent etiher the coordinates of a point the space, either a direction
  2522. * Reminder: Babylon.js uses a left handed forward facing system
  2523. */
  2524. var Vector3 = /** @class */ (function () {
  2525. /**
  2526. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2527. * @param x defines the first coordinates (on X axis)
  2528. * @param y defines the second coordinates (on Y axis)
  2529. * @param z defines the third coordinates (on Z axis)
  2530. */
  2531. function Vector3(
  2532. /**
  2533. * Defines the first coordinates (on X axis)
  2534. */
  2535. x,
  2536. /**
  2537. * Defines the second coordinates (on Y axis)
  2538. */
  2539. y,
  2540. /**
  2541. * Defines the third coordinates (on Z axis)
  2542. */
  2543. z) {
  2544. this.x = x;
  2545. this.y = y;
  2546. this.z = z;
  2547. }
  2548. /**
  2549. * Creates a string representation of the Vector3
  2550. * @returns a string with the Vector3 coordinates.
  2551. */
  2552. Vector3.prototype.toString = function () {
  2553. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2554. };
  2555. /**
  2556. * Gets the class name
  2557. * @returns the string "Vector3"
  2558. */
  2559. Vector3.prototype.getClassName = function () {
  2560. return "Vector3";
  2561. };
  2562. /**
  2563. * Creates the Vector3 hash code
  2564. * @returns a number which tends to be unique between Vector3 instances
  2565. */
  2566. Vector3.prototype.getHashCode = function () {
  2567. var hash = this.x || 0;
  2568. hash = (hash * 397) ^ (this.y || 0);
  2569. hash = (hash * 397) ^ (this.z || 0);
  2570. return hash;
  2571. };
  2572. // Operators
  2573. /**
  2574. * Creates an array containing three elements : the coordinates of the Vector3
  2575. * @returns a new array of numbers
  2576. */
  2577. Vector3.prototype.asArray = function () {
  2578. var result = [];
  2579. this.toArray(result, 0);
  2580. return result;
  2581. };
  2582. /**
  2583. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2584. * @param array defines the destination array
  2585. * @param index defines the offset in the destination array
  2586. * @returns the current Vector3
  2587. */
  2588. Vector3.prototype.toArray = function (array, index) {
  2589. if (index === void 0) { index = 0; }
  2590. array[index] = this.x;
  2591. array[index + 1] = this.y;
  2592. array[index + 2] = this.z;
  2593. return this;
  2594. };
  2595. /**
  2596. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2597. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2598. */
  2599. Vector3.prototype.toQuaternion = function () {
  2600. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2601. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2602. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2603. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2604. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2605. var cosy = Math.cos(this.y * 0.5);
  2606. var siny = Math.sin(this.y * 0.5);
  2607. result.x = coszMinusx * siny;
  2608. result.y = -sinzMinusx * siny;
  2609. result.z = sinxPlusz * cosy;
  2610. result.w = cosxPlusz * cosy;
  2611. return result;
  2612. };
  2613. /**
  2614. * Adds the passed vector to the current Vector3
  2615. * @param otherVector defines the second operand
  2616. * @returns the current updated Vector3
  2617. */
  2618. Vector3.prototype.addInPlace = function (otherVector) {
  2619. this.x += otherVector.x;
  2620. this.y += otherVector.y;
  2621. this.z += otherVector.z;
  2622. return this;
  2623. };
  2624. /**
  2625. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2626. * @param otherVector defines the second operand
  2627. * @returns the resulting Vector3
  2628. */
  2629. Vector3.prototype.add = function (otherVector) {
  2630. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2631. };
  2632. /**
  2633. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2634. * @param otherVector defines the second operand
  2635. * @param result defines the Vector3 object where to store the result
  2636. * @returns the current Vector3
  2637. */
  2638. Vector3.prototype.addToRef = function (otherVector, result) {
  2639. result.x = this.x + otherVector.x;
  2640. result.y = this.y + otherVector.y;
  2641. result.z = this.z + otherVector.z;
  2642. return this;
  2643. };
  2644. /**
  2645. * Subtract the passed vector from the current Vector3
  2646. * @param otherVector defines the second operand
  2647. * @returns the current updated Vector3
  2648. */
  2649. Vector3.prototype.subtractInPlace = function (otherVector) {
  2650. this.x -= otherVector.x;
  2651. this.y -= otherVector.y;
  2652. this.z -= otherVector.z;
  2653. return this;
  2654. };
  2655. /**
  2656. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2657. * @param otherVector defines the second operand
  2658. * @returns the resulting Vector3
  2659. */
  2660. Vector3.prototype.subtract = function (otherVector) {
  2661. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2662. };
  2663. /**
  2664. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2665. * @param otherVector defines the second operand
  2666. * @param result defines the Vector3 object where to store the result
  2667. * @returns the current Vector3
  2668. */
  2669. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2670. result.x = this.x - otherVector.x;
  2671. result.y = this.y - otherVector.y;
  2672. result.z = this.z - otherVector.z;
  2673. return this;
  2674. };
  2675. /**
  2676. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2677. * @param x defines the x coordinate of the operand
  2678. * @param y defines the y coordinate of the operand
  2679. * @param z defines the z coordinate of the operand
  2680. * @returns the resulting Vector3
  2681. */
  2682. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2683. return new Vector3(this.x - x, this.y - y, this.z - z);
  2684. };
  2685. /**
  2686. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2687. * @param x defines the x coordinate of the operand
  2688. * @param y defines the y coordinate of the operand
  2689. * @param z defines the z coordinate of the operand
  2690. * @param result defines the Vector3 object where to store the result
  2691. * @returns the current Vector3
  2692. */
  2693. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2694. result.x = this.x - x;
  2695. result.y = this.y - y;
  2696. result.z = this.z - z;
  2697. return this;
  2698. };
  2699. /**
  2700. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2701. * @returns a new Vector3
  2702. */
  2703. Vector3.prototype.negate = function () {
  2704. return new Vector3(-this.x, -this.y, -this.z);
  2705. };
  2706. /**
  2707. * Multiplies the Vector3 coordinates by the float "scale"
  2708. * @param scale defines the multiplier factor
  2709. * @returns the current updated Vector3
  2710. */
  2711. Vector3.prototype.scaleInPlace = function (scale) {
  2712. this.x *= scale;
  2713. this.y *= scale;
  2714. this.z *= scale;
  2715. return this;
  2716. };
  2717. /**
  2718. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2719. * @param scale defines the multiplier factor
  2720. * @returns a new Vector3
  2721. */
  2722. Vector3.prototype.scale = function (scale) {
  2723. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2724. };
  2725. /**
  2726. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2727. * @param scale defines the multiplier factor
  2728. * @param result defines the Vector3 object where to store the result
  2729. * @returns the current Vector3
  2730. */
  2731. Vector3.prototype.scaleToRef = function (scale, result) {
  2732. result.x = this.x * scale;
  2733. result.y = this.y * scale;
  2734. result.z = this.z * scale;
  2735. return this;
  2736. };
  2737. /**
  2738. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2739. * @param otherVector defines the second operand
  2740. * @returns true if both vectors are equals
  2741. */
  2742. Vector3.prototype.equals = function (otherVector) {
  2743. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2744. };
  2745. /**
  2746. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2747. * @param otherVector defines the second operand
  2748. * @param epsilon defines the minimal distance to define values as equals
  2749. * @returns true if both vectors are distant less than epsilon
  2750. */
  2751. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2752. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2753. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  2754. };
  2755. /**
  2756. * Returns true if the current Vector3 coordinates equals the passed floats
  2757. * @param x defines the x coordinate of the operand
  2758. * @param y defines the y coordinate of the operand
  2759. * @param z defines the z coordinate of the operand
  2760. * @returns true if both vectors are equals
  2761. */
  2762. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2763. return this.x === x && this.y === y && this.z === z;
  2764. };
  2765. /**
  2766. * Multiplies the current Vector3 coordinates by the passed ones
  2767. * @param otherVector defines the second operand
  2768. * @returns the current updated Vector3
  2769. */
  2770. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2771. this.x *= otherVector.x;
  2772. this.y *= otherVector.y;
  2773. this.z *= otherVector.z;
  2774. return this;
  2775. };
  2776. /**
  2777. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2778. * @param otherVector defines the second operand
  2779. * @returns the new Vector3
  2780. */
  2781. Vector3.prototype.multiply = function (otherVector) {
  2782. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2783. };
  2784. /**
  2785. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2786. * @param otherVector defines the second operand
  2787. * @param result defines the Vector3 object where to store the result
  2788. * @returns the current Vector3
  2789. */
  2790. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2791. result.x = this.x * otherVector.x;
  2792. result.y = this.y * otherVector.y;
  2793. result.z = this.z * otherVector.z;
  2794. return this;
  2795. };
  2796. /**
  2797. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2798. * @param x defines the x coordinate of the operand
  2799. * @param y defines the y coordinate of the operand
  2800. * @param z defines the z coordinate of the operand
  2801. * @returns the new Vector3
  2802. */
  2803. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2804. return new Vector3(this.x * x, this.y * y, this.z * z);
  2805. };
  2806. /**
  2807. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2808. * @param otherVector defines the second operand
  2809. * @returns the new Vector3
  2810. */
  2811. Vector3.prototype.divide = function (otherVector) {
  2812. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2813. };
  2814. /**
  2815. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2816. * @param otherVector defines the second operand
  2817. * @param result defines the Vector3 object where to store the result
  2818. * @returns the current Vector3
  2819. */
  2820. Vector3.prototype.divideToRef = function (otherVector, result) {
  2821. result.x = this.x / otherVector.x;
  2822. result.y = this.y / otherVector.y;
  2823. result.z = this.z / otherVector.z;
  2824. return this;
  2825. };
  2826. /**
  2827. * Divides the current Vector3 coordinates by the passed ones.
  2828. * @param otherVector defines the second operand
  2829. * @returns the current updated Vector3
  2830. */
  2831. Vector3.prototype.divideInPlace = function (otherVector) {
  2832. return this.divideToRef(otherVector, this);
  2833. };
  2834. /**
  2835. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2836. * @param other defines the second operand
  2837. * @returns the current updated Vector3
  2838. */
  2839. Vector3.prototype.minimizeInPlace = function (other) {
  2840. if (other.x < this.x)
  2841. this.x = other.x;
  2842. if (other.y < this.y)
  2843. this.y = other.y;
  2844. if (other.z < this.z)
  2845. this.z = other.z;
  2846. return this;
  2847. };
  2848. /**
  2849. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2850. * @param other defines the second operand
  2851. * @returns the current updated Vector3
  2852. */
  2853. Vector3.prototype.maximizeInPlace = function (other) {
  2854. if (other.x > this.x)
  2855. this.x = other.x;
  2856. if (other.y > this.y)
  2857. this.y = other.y;
  2858. if (other.z > this.z)
  2859. this.z = other.z;
  2860. return this;
  2861. };
  2862. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2863. /**
  2864. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2865. */
  2866. get: function () {
  2867. var absX = Math.abs(this.x);
  2868. var absY = Math.abs(this.y);
  2869. if (absX !== absY) {
  2870. return true;
  2871. }
  2872. var absZ = Math.abs(this.z);
  2873. if (absX !== absZ) {
  2874. return true;
  2875. }
  2876. if (absY !== absZ) {
  2877. return true;
  2878. }
  2879. return false;
  2880. },
  2881. enumerable: true,
  2882. configurable: true
  2883. });
  2884. // Properties
  2885. /**
  2886. * Gets the length of the Vector3
  2887. * @returns the length of the Vecto3
  2888. */
  2889. Vector3.prototype.length = function () {
  2890. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2891. };
  2892. /**
  2893. * Gets the squared length of the Vector3
  2894. * @returns squared length of the Vector3
  2895. */
  2896. Vector3.prototype.lengthSquared = function () {
  2897. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2898. };
  2899. /**
  2900. * Normalize the current Vector3.
  2901. * Please note that this is an in place operation.
  2902. * @returns the current updated Vector3
  2903. */
  2904. Vector3.prototype.normalize = function () {
  2905. var len = this.length();
  2906. if (len === 0 || len === 1.0)
  2907. return this;
  2908. var num = 1.0 / len;
  2909. this.x *= num;
  2910. this.y *= num;
  2911. this.z *= num;
  2912. return this;
  2913. };
  2914. /**
  2915. * Normalize the current Vector3 to a new vector
  2916. * @returns the new Vector3
  2917. */
  2918. Vector3.prototype.normalizeToNew = function () {
  2919. var normalized = new Vector3(0, 0, 0);
  2920. this.normalizeToRef(normalized);
  2921. return normalized;
  2922. };
  2923. /**
  2924. * Normalize the current Vector3 to the reference
  2925. * @param reference define the Vector3 to update
  2926. * @returns the updated Vector3
  2927. */
  2928. Vector3.prototype.normalizeToRef = function (reference) {
  2929. var len = this.length();
  2930. if (len === 0 || len === 1.0) {
  2931. reference.set(this.x, this.y, this.z);
  2932. return reference;
  2933. }
  2934. var scale = 1.0 / len;
  2935. this.scaleToRef(scale, reference);
  2936. return reference;
  2937. };
  2938. /**
  2939. * Creates a new Vector3 copied from the current Vector3
  2940. * @returns the new Vector3
  2941. */
  2942. Vector3.prototype.clone = function () {
  2943. return new Vector3(this.x, this.y, this.z);
  2944. };
  2945. /**
  2946. * Copies the passed vector coordinates to the current Vector3 ones
  2947. * @param source defines the source Vector3
  2948. * @returns the current updated Vector3
  2949. */
  2950. Vector3.prototype.copyFrom = function (source) {
  2951. this.x = source.x;
  2952. this.y = source.y;
  2953. this.z = source.z;
  2954. return this;
  2955. };
  2956. /**
  2957. * Copies the passed floats to the current Vector3 coordinates
  2958. * @param x defines the x coordinate of the operand
  2959. * @param y defines the y coordinate of the operand
  2960. * @param z defines the z coordinate of the operand
  2961. * @returns the current updated Vector3
  2962. */
  2963. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2964. this.x = x;
  2965. this.y = y;
  2966. this.z = z;
  2967. return this;
  2968. };
  2969. /**
  2970. * Copies the passed floats to the current Vector3 coordinates
  2971. * @param x defines the x coordinate of the operand
  2972. * @param y defines the y coordinate of the operand
  2973. * @param z defines the z coordinate of the operand
  2974. * @returns the current updated Vector3
  2975. */
  2976. Vector3.prototype.set = function (x, y, z) {
  2977. return this.copyFromFloats(x, y, z);
  2978. };
  2979. // Statics
  2980. /**
  2981. * Get the clip factor between two vectors
  2982. * @param vector0 defines the first operand
  2983. * @param vector1 defines the second operand
  2984. * @param axis defines the axis to use
  2985. * @param size defines the size along the axis
  2986. * @returns the clip factor
  2987. */
  2988. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  2989. var d0 = Vector3.Dot(vector0, axis) - size;
  2990. var d1 = Vector3.Dot(vector1, axis) - size;
  2991. var s = d0 / (d0 - d1);
  2992. return s;
  2993. };
  2994. /**
  2995. * Get angle between two vectors
  2996. * @param vector0 angle between vector0 and vector1
  2997. * @param vector1 angle between vector0 and vector1
  2998. * @param normal direction of the normal
  2999. * @return the angle between vector0 and vector1
  3000. */
  3001. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3002. var v0 = vector0.clone().normalize();
  3003. var v1 = vector1.clone().normalize();
  3004. var dot = Vector3.Dot(v0, v1);
  3005. var n = Vector3.Cross(v0, v1);
  3006. if (Vector3.Dot(n, normal) > 0) {
  3007. return Math.acos(dot);
  3008. }
  3009. return -Math.acos(dot);
  3010. };
  3011. /**
  3012. * Returns a new Vector3 set from the index "offset" of the passed array
  3013. * @param array defines the source array
  3014. * @param offset defines the offset in the source array
  3015. * @returns the new Vector3
  3016. */
  3017. Vector3.FromArray = function (array, offset) {
  3018. if (!offset) {
  3019. offset = 0;
  3020. }
  3021. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3022. };
  3023. /**
  3024. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3025. * This function is deprecated. Use FromArray instead
  3026. * @param array defines the source array
  3027. * @param offset defines the offset in the source array
  3028. * @returns the new Vector3
  3029. */
  3030. Vector3.FromFloatArray = function (array, offset) {
  3031. return Vector3.FromArray(array, offset);
  3032. };
  3033. /**
  3034. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3035. * @param array defines the source array
  3036. * @param offset defines the offset in the source array
  3037. * @param result defines the Vector3 where to store the result
  3038. */
  3039. Vector3.FromArrayToRef = function (array, offset, result) {
  3040. result.x = array[offset];
  3041. result.y = array[offset + 1];
  3042. result.z = array[offset + 2];
  3043. };
  3044. /**
  3045. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3046. * This function is deprecated. Use FromArrayToRef instead.
  3047. * @param array defines the source array
  3048. * @param offset defines the offset in the source array
  3049. * @param result defines the Vector3 where to store the result
  3050. */
  3051. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3052. return Vector3.FromArrayToRef(array, offset, result);
  3053. };
  3054. /**
  3055. * Sets the passed vector "result" with the passed floats.
  3056. * @param x defines the x coordinate of the source
  3057. * @param y defines the y coordinate of the source
  3058. * @param z defines the z coordinate of the source
  3059. * @param result defines the Vector3 where to store the result
  3060. */
  3061. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3062. result.x = x;
  3063. result.y = y;
  3064. result.z = z;
  3065. };
  3066. /**
  3067. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3068. * @returns a new empty Vector3
  3069. */
  3070. Vector3.Zero = function () {
  3071. return new Vector3(0.0, 0.0, 0.0);
  3072. };
  3073. /**
  3074. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3075. * @returns a new unit Vector3
  3076. */
  3077. Vector3.One = function () {
  3078. return new Vector3(1.0, 1.0, 1.0);
  3079. };
  3080. /**
  3081. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3082. * @returns a new up Vector3
  3083. */
  3084. Vector3.Up = function () {
  3085. return new Vector3(0.0, 1.0, 0.0);
  3086. };
  3087. /**
  3088. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3089. * @returns a new forward Vector3
  3090. */
  3091. Vector3.Forward = function () {
  3092. return new Vector3(0.0, 0.0, 1.0);
  3093. };
  3094. /**
  3095. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3096. * @returns a new right Vector3
  3097. */
  3098. Vector3.Right = function () {
  3099. return new Vector3(1.0, 0.0, 0.0);
  3100. };
  3101. /**
  3102. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3103. * @returns a new left Vector3
  3104. */
  3105. Vector3.Left = function () {
  3106. return new Vector3(-1.0, 0.0, 0.0);
  3107. };
  3108. /**
  3109. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3110. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3111. * @param vector defines the Vector3 to transform
  3112. * @param transformation defines the transformation matrix
  3113. * @returns the transformed Vector3
  3114. */
  3115. Vector3.TransformCoordinates = function (vector, transformation) {
  3116. var result = Vector3.Zero();
  3117. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3118. return result;
  3119. };
  3120. /**
  3121. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3122. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3123. * @param vector defines the Vector3 to transform
  3124. * @param transformation defines the transformation matrix
  3125. * @param result defines the Vector3 where to store the result
  3126. */
  3127. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3128. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3129. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3130. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3131. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3132. result.x = x / w;
  3133. result.y = y / w;
  3134. result.z = z / w;
  3135. };
  3136. /**
  3137. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3138. * This method computes tranformed coordinates only, not transformed direction vectors
  3139. * @param x define the x coordinate of the source vector
  3140. * @param y define the y coordinate of the source vector
  3141. * @param z define the z coordinate of the source vector
  3142. * @param transformation defines the transformation matrix
  3143. * @param result defines the Vector3 where to store the result
  3144. */
  3145. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3146. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3147. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3148. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3149. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3150. result.x = rx / rw;
  3151. result.y = ry / rw;
  3152. result.z = rz / rw;
  3153. };
  3154. /**
  3155. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3156. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3157. * @param vector defines the Vector3 to transform
  3158. * @param transformation defines the transformation matrix
  3159. * @returns the new Vector3
  3160. */
  3161. Vector3.TransformNormal = function (vector, transformation) {
  3162. var result = Vector3.Zero();
  3163. Vector3.TransformNormalToRef(vector, transformation, result);
  3164. return result;
  3165. };
  3166. /**
  3167. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3168. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3169. * @param vector defines the Vector3 to transform
  3170. * @param transformation defines the transformation matrix
  3171. * @param result defines the Vector3 where to store the result
  3172. */
  3173. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3174. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3175. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3176. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3177. result.x = x;
  3178. result.y = y;
  3179. result.z = z;
  3180. };
  3181. /**
  3182. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3183. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3184. * @param x define the x coordinate of the source vector
  3185. * @param y define the y coordinate of the source vector
  3186. * @param z define the z coordinate of the source vector
  3187. * @param transformation defines the transformation matrix
  3188. * @param result defines the Vector3 where to store the result
  3189. */
  3190. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3191. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3192. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3193. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3194. };
  3195. /**
  3196. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3197. * @param value1 defines the first control point
  3198. * @param value2 defines the second control point
  3199. * @param value3 defines the third control point
  3200. * @param value4 defines the fourth control point
  3201. * @param amount defines the amount on the spline to use
  3202. * @returns the new Vector3
  3203. */
  3204. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3205. var squared = amount * amount;
  3206. var cubed = amount * squared;
  3207. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3208. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3209. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3210. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3211. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3212. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3213. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3214. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3215. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3216. return new Vector3(x, y, z);
  3217. };
  3218. /**
  3219. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  3220. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3221. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3222. * @param value defines the current value
  3223. * @param min defines the lower range value
  3224. * @param max defines the upper range value
  3225. * @returns the new Vector3
  3226. */
  3227. Vector3.Clamp = function (value, min, max) {
  3228. var x = value.x;
  3229. x = (x > max.x) ? max.x : x;
  3230. x = (x < min.x) ? min.x : x;
  3231. var y = value.y;
  3232. y = (y > max.y) ? max.y : y;
  3233. y = (y < min.y) ? min.y : y;
  3234. var z = value.z;
  3235. z = (z > max.z) ? max.z : z;
  3236. z = (z < min.z) ? min.z : z;
  3237. return new Vector3(x, y, z);
  3238. };
  3239. /**
  3240. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3241. * @param value1 defines the first control point
  3242. * @param tangent1 defines the first tangent vector
  3243. * @param value2 defines the second control point
  3244. * @param tangent2 defines the second tangent vector
  3245. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3246. * @returns the new Vector3
  3247. */
  3248. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3249. var squared = amount * amount;
  3250. var cubed = amount * squared;
  3251. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3252. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3253. var part3 = (cubed - (2.0 * squared)) + amount;
  3254. var part4 = cubed - squared;
  3255. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3256. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3257. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3258. return new Vector3(x, y, z);
  3259. };
  3260. /**
  3261. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3262. * @param start defines the start value
  3263. * @param end defines the end value
  3264. * @param amount max defines amount between both (between 0 and 1)
  3265. * @returns the new Vector3
  3266. */
  3267. Vector3.Lerp = function (start, end, amount) {
  3268. var result = new Vector3(0, 0, 0);
  3269. Vector3.LerpToRef(start, end, amount, result);
  3270. return result;
  3271. };
  3272. /**
  3273. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3274. * @param start defines the start value
  3275. * @param end defines the end value
  3276. * @param amount max defines amount between both (between 0 and 1)
  3277. * @param result defines the Vector3 where to store the result
  3278. */
  3279. Vector3.LerpToRef = function (start, end, amount, result) {
  3280. result.x = start.x + ((end.x - start.x) * amount);
  3281. result.y = start.y + ((end.y - start.y) * amount);
  3282. result.z = start.z + ((end.z - start.z) * amount);
  3283. };
  3284. /**
  3285. * Returns the dot product (float) between the vectors "left" and "right"
  3286. * @param left defines the left operand
  3287. * @param right defines the right operand
  3288. * @returns the dot product
  3289. */
  3290. Vector3.Dot = function (left, right) {
  3291. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3292. };
  3293. /**
  3294. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3295. * The cross product is then orthogonal to both "left" and "right"
  3296. * @param left defines the left operand
  3297. * @param right defines the right operand
  3298. * @returns the cross product
  3299. */
  3300. Vector3.Cross = function (left, right) {
  3301. var result = Vector3.Zero();
  3302. Vector3.CrossToRef(left, right, result);
  3303. return result;
  3304. };
  3305. /**
  3306. * Sets the passed vector "result" with the cross product of "left" and "right"
  3307. * The cross product is then orthogonal to both "left" and "right"
  3308. * @param left defines the left operand
  3309. * @param right defines the right operand
  3310. * @param result defines the Vector3 where to store the result
  3311. */
  3312. Vector3.CrossToRef = function (left, right, result) {
  3313. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3314. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3315. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3316. result.copyFrom(MathTmp.Vector3[0]);
  3317. };
  3318. /**
  3319. * Returns a new Vector3 as the normalization of the passed vector
  3320. * @param vector defines the Vector3 to normalize
  3321. * @returns the new Vector3
  3322. */
  3323. Vector3.Normalize = function (vector) {
  3324. var result = Vector3.Zero();
  3325. Vector3.NormalizeToRef(vector, result);
  3326. return result;
  3327. };
  3328. /**
  3329. * Sets the passed vector "result" with the normalization of the passed first vector
  3330. * @param vector defines the Vector3 to normalize
  3331. * @param result defines the Vector3 where to store the result
  3332. */
  3333. Vector3.NormalizeToRef = function (vector, result) {
  3334. result.copyFrom(vector);
  3335. result.normalize();
  3336. };
  3337. /**
  3338. * Project a Vector3 onto screen space
  3339. * @param vector defines the Vector3 to project
  3340. * @param world defines the world matrix to use
  3341. * @param transform defines the transform (view x projection) matrix to use
  3342. * @param viewport defines the screen viewport to use
  3343. * @returns the new Vector3
  3344. */
  3345. Vector3.Project = function (vector, world, transform, viewport) {
  3346. var cw = viewport.width;
  3347. var ch = viewport.height;
  3348. var cx = viewport.x;
  3349. var cy = viewport.y;
  3350. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3351. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  3352. var matrix = MathTmp.Matrix[0];
  3353. world.multiplyToRef(transform, matrix);
  3354. matrix.multiplyToRef(viewportMatrix, matrix);
  3355. return Vector3.TransformCoordinates(vector, matrix);
  3356. };
  3357. /**
  3358. * Unproject from screen space to object space
  3359. * @param source defines the screen space Vector3 to use
  3360. * @param viewportWidth defines the current width of the viewport
  3361. * @param viewportHeight defines the current height of the viewport
  3362. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3363. * @param transform defines the transform (view x projection) matrix to use
  3364. * @returns the new Vector3
  3365. */
  3366. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3367. var matrix = MathTmp.Matrix[0];
  3368. world.multiplyToRef(transform, matrix);
  3369. matrix.invert();
  3370. source.x = source.x / viewportWidth * 2 - 1;
  3371. source.y = -(source.y / viewportHeight * 2 - 1);
  3372. var vector = Vector3.TransformCoordinates(source, matrix);
  3373. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3374. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3375. vector = vector.scale(1.0 / num);
  3376. }
  3377. return vector;
  3378. };
  3379. /**
  3380. * Unproject from screen space to object space
  3381. * @param source defines the screen space Vector3 to use
  3382. * @param viewportWidth defines the current width of the viewport
  3383. * @param viewportHeight defines the current height of the viewport
  3384. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3385. * @param view defines the view matrix to use
  3386. * @param projection defines the projection matrix to use
  3387. * @returns the new Vector3
  3388. */
  3389. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3390. var result = Vector3.Zero();
  3391. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3392. return result;
  3393. };
  3394. /**
  3395. * Unproject from screen space to object space
  3396. * @param source defines the screen space Vector3 to use
  3397. * @param viewportWidth defines the current width of the viewport
  3398. * @param viewportHeight defines the current height of the viewport
  3399. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3400. * @param view defines the view matrix to use
  3401. * @param projection defines the projection matrix to use
  3402. * @param result defines the Vector3 where to store the result
  3403. */
  3404. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3405. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3406. };
  3407. /**
  3408. * Unproject from screen space to object space
  3409. * @param sourceX defines the screen space x coordinate to use
  3410. * @param sourceY defines the screen space y coordinate to use
  3411. * @param sourceZ defines the screen space z coordinate to use
  3412. * @param viewportWidth defines the current width of the viewport
  3413. * @param viewportHeight defines the current height of the viewport
  3414. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3415. * @param view defines the view matrix to use
  3416. * @param projection defines the projection matrix to use
  3417. * @param result defines the Vector3 where to store the result
  3418. */
  3419. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3420. var matrix = MathTmp.Matrix[0];
  3421. world.multiplyToRef(view, matrix);
  3422. matrix.multiplyToRef(projection, matrix);
  3423. matrix.invert();
  3424. var screenSource = MathTmp.Vector3[0];
  3425. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3426. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3427. screenSource.z = 2 * sourceZ - 1.0;
  3428. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3429. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3430. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3431. result.scaleInPlace(1.0 / num);
  3432. }
  3433. };
  3434. /**
  3435. * Gets the minimal coordinate values between two Vector3
  3436. * @param left defines the first operand
  3437. * @param right defines the second operand
  3438. * @returns the new Vector3
  3439. */
  3440. Vector3.Minimize = function (left, right) {
  3441. var min = left.clone();
  3442. min.minimizeInPlace(right);
  3443. return min;
  3444. };
  3445. /**
  3446. * Gets the maximal coordinate values between two Vector3
  3447. * @param left defines the first operand
  3448. * @param right defines the second operand
  3449. * @returns the new Vector3
  3450. */
  3451. Vector3.Maximize = function (left, right) {
  3452. var max = left.clone();
  3453. max.maximizeInPlace(right);
  3454. return max;
  3455. };
  3456. /**
  3457. * Returns the distance between the vectors "value1" and "value2"
  3458. * @param value1 defines the first operand
  3459. * @param value2 defines the second operand
  3460. * @returns the distance
  3461. */
  3462. Vector3.Distance = function (value1, value2) {
  3463. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3464. };
  3465. /**
  3466. * Returns the squared distance between the vectors "value1" and "value2"
  3467. * @param value1 defines the first operand
  3468. * @param value2 defines the second operand
  3469. * @returns the squared distance
  3470. */
  3471. Vector3.DistanceSquared = function (value1, value2) {
  3472. var x = value1.x - value2.x;
  3473. var y = value1.y - value2.y;
  3474. var z = value1.z - value2.z;
  3475. return (x * x) + (y * y) + (z * z);
  3476. };
  3477. /**
  3478. * Returns a new Vector3 located at the center between "value1" and "value2"
  3479. * @param value1 defines the first operand
  3480. * @param value2 defines the second operand
  3481. * @returns the new Vector3
  3482. */
  3483. Vector3.Center = function (value1, value2) {
  3484. var center = value1.add(value2);
  3485. center.scaleInPlace(0.5);
  3486. return center;
  3487. };
  3488. /**
  3489. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3490. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3491. * to something in order to rotate it from its local system to the given target system
  3492. * Note: axis1, axis2 and axis3 are normalized during this operation
  3493. * @param axis1 defines the first axis
  3494. * @param axis2 defines the second axis
  3495. * @param axis3 defines the third axis
  3496. * @returns a new Vector3
  3497. */
  3498. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3499. var rotation = Vector3.Zero();
  3500. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3501. return rotation;
  3502. };
  3503. /**
  3504. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3505. * @param axis1 defines the first axis
  3506. * @param axis2 defines the second axis
  3507. * @param axis3 defines the third axis
  3508. * @param ref defines the Vector3 where to store the result
  3509. */
  3510. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3511. var quat = MathTmp.Quaternion[0];
  3512. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3513. quat.toEulerAnglesToRef(ref);
  3514. };
  3515. return Vector3;
  3516. }());
  3517. BABYLON.Vector3 = Vector3;
  3518. //Vector4 class created for EulerAngle class conversion to Quaternion
  3519. var Vector4 = /** @class */ (function () {
  3520. /**
  3521. * Creates a Vector4 object from the passed floats.
  3522. */
  3523. function Vector4(x, y, z, w) {
  3524. this.x = x;
  3525. this.y = y;
  3526. this.z = z;
  3527. this.w = w;
  3528. }
  3529. /**
  3530. * Returns the string with the Vector4 coordinates.
  3531. */
  3532. Vector4.prototype.toString = function () {
  3533. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3534. };
  3535. /**
  3536. * Returns the string "Vector4".
  3537. */
  3538. Vector4.prototype.getClassName = function () {
  3539. return "Vector4";
  3540. };
  3541. /**
  3542. * Returns the Vector4 hash code.
  3543. */
  3544. Vector4.prototype.getHashCode = function () {
  3545. var hash = this.x || 0;
  3546. hash = (hash * 397) ^ (this.y || 0);
  3547. hash = (hash * 397) ^ (this.z || 0);
  3548. hash = (hash * 397) ^ (this.w || 0);
  3549. return hash;
  3550. };
  3551. // Operators
  3552. /**
  3553. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3554. */
  3555. Vector4.prototype.asArray = function () {
  3556. var result = new Array();
  3557. this.toArray(result, 0);
  3558. return result;
  3559. };
  3560. /**
  3561. * Populates the passed array from the passed index with the Vector4 coordinates.
  3562. * Returns the Vector4.
  3563. */
  3564. Vector4.prototype.toArray = function (array, index) {
  3565. if (index === undefined) {
  3566. index = 0;
  3567. }
  3568. array[index] = this.x;
  3569. array[index + 1] = this.y;
  3570. array[index + 2] = this.z;
  3571. array[index + 3] = this.w;
  3572. return this;
  3573. };
  3574. /**
  3575. * Adds the passed vector to the current Vector4.
  3576. * Returns the updated Vector4.
  3577. */
  3578. Vector4.prototype.addInPlace = function (otherVector) {
  3579. this.x += otherVector.x;
  3580. this.y += otherVector.y;
  3581. this.z += otherVector.z;
  3582. this.w += otherVector.w;
  3583. return this;
  3584. };
  3585. /**
  3586. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3587. */
  3588. Vector4.prototype.add = function (otherVector) {
  3589. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3590. };
  3591. /**
  3592. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3593. * Returns the current Vector4.
  3594. */
  3595. Vector4.prototype.addToRef = function (otherVector, result) {
  3596. result.x = this.x + otherVector.x;
  3597. result.y = this.y + otherVector.y;
  3598. result.z = this.z + otherVector.z;
  3599. result.w = this.w + otherVector.w;
  3600. return this;
  3601. };
  3602. /**
  3603. * Subtract in place the passed vector from the current Vector4.
  3604. * Returns the updated Vector4.
  3605. */
  3606. Vector4.prototype.subtractInPlace = function (otherVector) {
  3607. this.x -= otherVector.x;
  3608. this.y -= otherVector.y;
  3609. this.z -= otherVector.z;
  3610. this.w -= otherVector.w;
  3611. return this;
  3612. };
  3613. /**
  3614. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3615. */
  3616. Vector4.prototype.subtract = function (otherVector) {
  3617. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3618. };
  3619. /**
  3620. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3621. * Returns the current Vector4.
  3622. */
  3623. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3624. result.x = this.x - otherVector.x;
  3625. result.y = this.y - otherVector.y;
  3626. result.z = this.z - otherVector.z;
  3627. result.w = this.w - otherVector.w;
  3628. return this;
  3629. };
  3630. /**
  3631. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3632. */
  3633. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3634. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3635. };
  3636. /**
  3637. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3638. * Returns the current Vector4.
  3639. */
  3640. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3641. result.x = this.x - x;
  3642. result.y = this.y - y;
  3643. result.z = this.z - z;
  3644. result.w = this.w - w;
  3645. return this;
  3646. };
  3647. /**
  3648. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3649. */
  3650. Vector4.prototype.negate = function () {
  3651. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3652. };
  3653. /**
  3654. * Multiplies the current Vector4 coordinates by scale (float).
  3655. * Returns the updated Vector4.
  3656. */
  3657. Vector4.prototype.scaleInPlace = function (scale) {
  3658. this.x *= scale;
  3659. this.y *= scale;
  3660. this.z *= scale;
  3661. this.w *= scale;
  3662. return this;
  3663. };
  3664. /**
  3665. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3666. */
  3667. Vector4.prototype.scale = function (scale) {
  3668. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3669. };
  3670. /**
  3671. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3672. * Returns the current Vector4.
  3673. */
  3674. Vector4.prototype.scaleToRef = function (scale, result) {
  3675. result.x = this.x * scale;
  3676. result.y = this.y * scale;
  3677. result.z = this.z * scale;
  3678. result.w = this.w * scale;
  3679. return this;
  3680. };
  3681. /**
  3682. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3683. */
  3684. Vector4.prototype.equals = function (otherVector) {
  3685. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3686. };
  3687. /**
  3688. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3689. */
  3690. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3691. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3692. return otherVector
  3693. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3694. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3695. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3696. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3697. };
  3698. /**
  3699. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3700. */
  3701. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3702. return this.x === x && this.y === y && this.z === z && this.w === w;
  3703. };
  3704. /**
  3705. * Multiplies in place the current Vector4 by the passed one.
  3706. * Returns the updated Vector4.
  3707. */
  3708. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3709. this.x *= otherVector.x;
  3710. this.y *= otherVector.y;
  3711. this.z *= otherVector.z;
  3712. this.w *= otherVector.w;
  3713. return this;
  3714. };
  3715. /**
  3716. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3717. */
  3718. Vector4.prototype.multiply = function (otherVector) {
  3719. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3720. };
  3721. /**
  3722. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3723. * Returns the current Vector4.
  3724. */
  3725. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3726. result.x = this.x * otherVector.x;
  3727. result.y = this.y * otherVector.y;
  3728. result.z = this.z * otherVector.z;
  3729. result.w = this.w * otherVector.w;
  3730. return this;
  3731. };
  3732. /**
  3733. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3734. */
  3735. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3736. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3737. };
  3738. /**
  3739. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3740. */
  3741. Vector4.prototype.divide = function (otherVector) {
  3742. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3743. };
  3744. /**
  3745. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3746. * Returns the current Vector4.
  3747. */
  3748. Vector4.prototype.divideToRef = function (otherVector, result) {
  3749. result.x = this.x / otherVector.x;
  3750. result.y = this.y / otherVector.y;
  3751. result.z = this.z / otherVector.z;
  3752. result.w = this.w / otherVector.w;
  3753. return this;
  3754. };
  3755. /**
  3756. * Divides the current Vector3 coordinates by the passed ones.
  3757. * @returns the updated Vector3.
  3758. */
  3759. Vector4.prototype.divideInPlace = function (otherVector) {
  3760. return this.divideToRef(otherVector, this);
  3761. };
  3762. /**
  3763. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3764. * @param other defines the second operand
  3765. * @returns the current updated Vector4
  3766. */
  3767. Vector4.prototype.minimizeInPlace = function (other) {
  3768. if (other.x < this.x)
  3769. this.x = other.x;
  3770. if (other.y < this.y)
  3771. this.y = other.y;
  3772. if (other.z < this.z)
  3773. this.z = other.z;
  3774. if (other.w < this.w)
  3775. this.w = other.w;
  3776. return this;
  3777. };
  3778. /**
  3779. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3780. * @param other defines the second operand
  3781. * @returns the current updated Vector4
  3782. */
  3783. Vector4.prototype.maximizeInPlace = function (other) {
  3784. if (other.x > this.x)
  3785. this.x = other.x;
  3786. if (other.y > this.y)
  3787. this.y = other.y;
  3788. if (other.z > this.z)
  3789. this.z = other.z;
  3790. if (other.w > this.w)
  3791. this.w = other.w;
  3792. return this;
  3793. };
  3794. // Properties
  3795. /**
  3796. * Returns the Vector4 length (float).
  3797. */
  3798. Vector4.prototype.length = function () {
  3799. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3800. };
  3801. /**
  3802. * Returns the Vector4 squared length (float).
  3803. */
  3804. Vector4.prototype.lengthSquared = function () {
  3805. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3806. };
  3807. // Methods
  3808. /**
  3809. * Normalizes in place the Vector4.
  3810. * Returns the updated Vector4.
  3811. */
  3812. Vector4.prototype.normalize = function () {
  3813. var len = this.length();
  3814. if (len === 0)
  3815. return this;
  3816. var num = 1.0 / len;
  3817. this.x *= num;
  3818. this.y *= num;
  3819. this.z *= num;
  3820. this.w *= num;
  3821. return this;
  3822. };
  3823. /**
  3824. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3825. */
  3826. Vector4.prototype.toVector3 = function () {
  3827. return new Vector3(this.x, this.y, this.z);
  3828. };
  3829. /**
  3830. * Returns a new Vector4 copied from the current one.
  3831. */
  3832. Vector4.prototype.clone = function () {
  3833. return new Vector4(this.x, this.y, this.z, this.w);
  3834. };
  3835. /**
  3836. * Updates the current Vector4 with the passed one coordinates.
  3837. * Returns the updated Vector4.
  3838. */
  3839. Vector4.prototype.copyFrom = function (source) {
  3840. this.x = source.x;
  3841. this.y = source.y;
  3842. this.z = source.z;
  3843. this.w = source.w;
  3844. return this;
  3845. };
  3846. /**
  3847. * Updates the current Vector4 coordinates with the passed floats.
  3848. * Returns the updated Vector4.
  3849. */
  3850. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3851. this.x = x;
  3852. this.y = y;
  3853. this.z = z;
  3854. this.w = w;
  3855. return this;
  3856. };
  3857. /**
  3858. * Updates the current Vector4 coordinates with the passed floats.
  3859. * Returns the updated Vector4.
  3860. */
  3861. Vector4.prototype.set = function (x, y, z, w) {
  3862. return this.copyFromFloats(x, y, z, w);
  3863. };
  3864. // Statics
  3865. /**
  3866. * Returns a new Vector4 set from the starting index of the passed array.
  3867. */
  3868. Vector4.FromArray = function (array, offset) {
  3869. if (!offset) {
  3870. offset = 0;
  3871. }
  3872. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3873. };
  3874. /**
  3875. * Updates the passed vector "result" from the starting index of the passed array.
  3876. */
  3877. Vector4.FromArrayToRef = function (array, offset, result) {
  3878. result.x = array[offset];
  3879. result.y = array[offset + 1];
  3880. result.z = array[offset + 2];
  3881. result.w = array[offset + 3];
  3882. };
  3883. /**
  3884. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3885. */
  3886. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3887. Vector4.FromArrayToRef(array, offset, result);
  3888. };
  3889. /**
  3890. * Updates the passed vector "result" coordinates from the passed floats.
  3891. */
  3892. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3893. result.x = x;
  3894. result.y = y;
  3895. result.z = z;
  3896. result.w = w;
  3897. };
  3898. /**
  3899. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3900. */
  3901. Vector4.Zero = function () {
  3902. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3903. };
  3904. /**
  3905. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3906. */
  3907. Vector4.One = function () {
  3908. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3909. };
  3910. /**
  3911. * Returns a new normalized Vector4 from the passed one.
  3912. */
  3913. Vector4.Normalize = function (vector) {
  3914. var result = Vector4.Zero();
  3915. Vector4.NormalizeToRef(vector, result);
  3916. return result;
  3917. };
  3918. /**
  3919. * Updates the passed vector "result" from the normalization of the passed one.
  3920. */
  3921. Vector4.NormalizeToRef = function (vector, result) {
  3922. result.copyFrom(vector);
  3923. result.normalize();
  3924. };
  3925. Vector4.Minimize = function (left, right) {
  3926. var min = left.clone();
  3927. min.minimizeInPlace(right);
  3928. return min;
  3929. };
  3930. Vector4.Maximize = function (left, right) {
  3931. var max = left.clone();
  3932. max.maximizeInPlace(right);
  3933. return max;
  3934. };
  3935. /**
  3936. * Returns the distance (float) between the vectors "value1" and "value2".
  3937. */
  3938. Vector4.Distance = function (value1, value2) {
  3939. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3940. };
  3941. /**
  3942. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3943. */
  3944. Vector4.DistanceSquared = function (value1, value2) {
  3945. var x = value1.x - value2.x;
  3946. var y = value1.y - value2.y;
  3947. var z = value1.z - value2.z;
  3948. var w = value1.w - value2.w;
  3949. return (x * x) + (y * y) + (z * z) + (w * w);
  3950. };
  3951. /**
  3952. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3953. */
  3954. Vector4.Center = function (value1, value2) {
  3955. var center = value1.add(value2);
  3956. center.scaleInPlace(0.5);
  3957. return center;
  3958. };
  3959. /**
  3960. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3961. * This methods computes transformed normalized direction vectors only.
  3962. */
  3963. Vector4.TransformNormal = function (vector, transformation) {
  3964. var result = Vector4.Zero();
  3965. Vector4.TransformNormalToRef(vector, transformation, result);
  3966. return result;
  3967. };
  3968. /**
  3969. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3970. * This methods computes transformed normalized direction vectors only.
  3971. */
  3972. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3973. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3974. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3975. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3976. result.x = x;
  3977. result.y = y;
  3978. result.z = z;
  3979. result.w = vector.w;
  3980. };
  3981. /**
  3982. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3983. * This methods computes transformed normalized direction vectors only.
  3984. */
  3985. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  3986. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3987. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3988. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3989. result.w = w;
  3990. };
  3991. return Vector4;
  3992. }());
  3993. BABYLON.Vector4 = Vector4;
  3994. var Size = /** @class */ (function () {
  3995. /**
  3996. * Creates a Size object from the passed width and height (floats).
  3997. */
  3998. function Size(width, height) {
  3999. this.width = width;
  4000. this.height = height;
  4001. }
  4002. // Returns a string with the Size width and height.
  4003. Size.prototype.toString = function () {
  4004. return "{W: " + this.width + ", H: " + this.height + "}";
  4005. };
  4006. /**
  4007. * Returns the string "Size"
  4008. */
  4009. Size.prototype.getClassName = function () {
  4010. return "Size";
  4011. };
  4012. /**
  4013. * Returns the Size hash code.
  4014. */
  4015. Size.prototype.getHashCode = function () {
  4016. var hash = this.width || 0;
  4017. hash = (hash * 397) ^ (this.height || 0);
  4018. return hash;
  4019. };
  4020. /**
  4021. * Updates the current size from the passed one.
  4022. * Returns the updated Size.
  4023. */
  4024. Size.prototype.copyFrom = function (src) {
  4025. this.width = src.width;
  4026. this.height = src.height;
  4027. };
  4028. /**
  4029. * Updates in place the current Size from the passed floats.
  4030. * Returns the updated Size.
  4031. */
  4032. Size.prototype.copyFromFloats = function (width, height) {
  4033. this.width = width;
  4034. this.height = height;
  4035. return this;
  4036. };
  4037. /**
  4038. * Updates in place the current Size from the passed floats.
  4039. * Returns the updated Size.
  4040. */
  4041. Size.prototype.set = function (width, height) {
  4042. return this.copyFromFloats(width, height);
  4043. };
  4044. /**
  4045. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4046. */
  4047. Size.prototype.multiplyByFloats = function (w, h) {
  4048. return new Size(this.width * w, this.height * h);
  4049. };
  4050. /**
  4051. * Returns a new Size copied from the passed one.
  4052. */
  4053. Size.prototype.clone = function () {
  4054. return new Size(this.width, this.height);
  4055. };
  4056. /**
  4057. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4058. */
  4059. Size.prototype.equals = function (other) {
  4060. if (!other) {
  4061. return false;
  4062. }
  4063. return (this.width === other.width) && (this.height === other.height);
  4064. };
  4065. Object.defineProperty(Size.prototype, "surface", {
  4066. /**
  4067. * Returns the surface of the Size : width * height (float).
  4068. */
  4069. get: function () {
  4070. return this.width * this.height;
  4071. },
  4072. enumerable: true,
  4073. configurable: true
  4074. });
  4075. /**
  4076. * Returns a new Size set to (0.0, 0.0)
  4077. */
  4078. Size.Zero = function () {
  4079. return new Size(0.0, 0.0);
  4080. };
  4081. /**
  4082. * Returns a new Size set as the addition result of the current Size and the passed one.
  4083. */
  4084. Size.prototype.add = function (otherSize) {
  4085. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4086. return r;
  4087. };
  4088. /**
  4089. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4090. */
  4091. Size.prototype.subtract = function (otherSize) {
  4092. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4093. return r;
  4094. };
  4095. /**
  4096. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4097. */
  4098. Size.Lerp = function (start, end, amount) {
  4099. var w = start.width + ((end.width - start.width) * amount);
  4100. var h = start.height + ((end.height - start.height) * amount);
  4101. return new Size(w, h);
  4102. };
  4103. return Size;
  4104. }());
  4105. BABYLON.Size = Size;
  4106. var Quaternion = /** @class */ (function () {
  4107. /**
  4108. * Creates a new Quaternion from the passed floats.
  4109. */
  4110. function Quaternion(x, y, z, w) {
  4111. if (x === void 0) { x = 0.0; }
  4112. if (y === void 0) { y = 0.0; }
  4113. if (z === void 0) { z = 0.0; }
  4114. if (w === void 0) { w = 1.0; }
  4115. this.x = x;
  4116. this.y = y;
  4117. this.z = z;
  4118. this.w = w;
  4119. }
  4120. /**
  4121. * Returns a string with the Quaternion coordinates.
  4122. */
  4123. Quaternion.prototype.toString = function () {
  4124. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4125. };
  4126. /**
  4127. * Returns the string "Quaternion".
  4128. */
  4129. Quaternion.prototype.getClassName = function () {
  4130. return "Quaternion";
  4131. };
  4132. /**
  4133. * Returns the Quaternion hash code.
  4134. */
  4135. Quaternion.prototype.getHashCode = function () {
  4136. var hash = this.x || 0;
  4137. hash = (hash * 397) ^ (this.y || 0);
  4138. hash = (hash * 397) ^ (this.z || 0);
  4139. hash = (hash * 397) ^ (this.w || 0);
  4140. return hash;
  4141. };
  4142. /**
  4143. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4144. */
  4145. Quaternion.prototype.asArray = function () {
  4146. return [this.x, this.y, this.z, this.w];
  4147. };
  4148. /**
  4149. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4150. */
  4151. Quaternion.prototype.equals = function (otherQuaternion) {
  4152. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4153. };
  4154. /**
  4155. * Returns a new Quaternion copied from the current one.
  4156. */
  4157. Quaternion.prototype.clone = function () {
  4158. return new Quaternion(this.x, this.y, this.z, this.w);
  4159. };
  4160. /**
  4161. * Updates the current Quaternion from the passed one coordinates.
  4162. * Returns the updated Quaterion.
  4163. */
  4164. Quaternion.prototype.copyFrom = function (other) {
  4165. this.x = other.x;
  4166. this.y = other.y;
  4167. this.z = other.z;
  4168. this.w = other.w;
  4169. return this;
  4170. };
  4171. /**
  4172. * Updates the current Quaternion from the passed float coordinates.
  4173. * Returns the updated Quaterion.
  4174. */
  4175. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4176. this.x = x;
  4177. this.y = y;
  4178. this.z = z;
  4179. this.w = w;
  4180. return this;
  4181. };
  4182. /**
  4183. * Updates the current Quaternion from the passed float coordinates.
  4184. * Returns the updated Quaterion.
  4185. */
  4186. Quaternion.prototype.set = function (x, y, z, w) {
  4187. return this.copyFromFloats(x, y, z, w);
  4188. };
  4189. /**
  4190. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4191. */
  4192. Quaternion.prototype.add = function (other) {
  4193. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4194. };
  4195. /**
  4196. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4197. */
  4198. Quaternion.prototype.subtract = function (other) {
  4199. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4200. };
  4201. /**
  4202. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4203. */
  4204. Quaternion.prototype.scale = function (value) {
  4205. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4206. };
  4207. /**
  4208. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4209. */
  4210. Quaternion.prototype.multiply = function (q1) {
  4211. var result = new Quaternion(0, 0, 0, 1.0);
  4212. this.multiplyToRef(q1, result);
  4213. return result;
  4214. };
  4215. /**
  4216. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4217. * Returns the current Quaternion.
  4218. */
  4219. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4220. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4221. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4222. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4223. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4224. result.copyFromFloats(x, y, z, w);
  4225. return this;
  4226. };
  4227. /**
  4228. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4229. * Returns the updated Quaternion.
  4230. */
  4231. Quaternion.prototype.multiplyInPlace = function (q1) {
  4232. this.multiplyToRef(q1, this);
  4233. return this;
  4234. };
  4235. /**
  4236. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4237. * Returns the current Quaternion.
  4238. */
  4239. Quaternion.prototype.conjugateToRef = function (ref) {
  4240. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4241. return this;
  4242. };
  4243. /**
  4244. * Conjugates in place the current Quaternion.
  4245. * Returns the updated Quaternion.
  4246. */
  4247. Quaternion.prototype.conjugateInPlace = function () {
  4248. this.x *= -1;
  4249. this.y *= -1;
  4250. this.z *= -1;
  4251. return this;
  4252. };
  4253. /**
  4254. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4255. */
  4256. Quaternion.prototype.conjugate = function () {
  4257. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4258. return result;
  4259. };
  4260. /**
  4261. * Returns the Quaternion length (float).
  4262. */
  4263. Quaternion.prototype.length = function () {
  4264. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4265. };
  4266. /**
  4267. * Normalize in place the current Quaternion.
  4268. * Returns the updated Quaternion.
  4269. */
  4270. Quaternion.prototype.normalize = function () {
  4271. var length = 1.0 / this.length();
  4272. this.x *= length;
  4273. this.y *= length;
  4274. this.z *= length;
  4275. this.w *= length;
  4276. return this;
  4277. };
  4278. /**
  4279. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4280. */
  4281. Quaternion.prototype.toEulerAngles = function (order) {
  4282. if (order === void 0) { order = "YZX"; }
  4283. var result = Vector3.Zero();
  4284. this.toEulerAnglesToRef(result, order);
  4285. return result;
  4286. };
  4287. /**
  4288. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4289. * Returns the current Quaternion.
  4290. */
  4291. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4292. if (order === void 0) { order = "YZX"; }
  4293. var qz = this.z;
  4294. var qx = this.x;
  4295. var qy = this.y;
  4296. var qw = this.w;
  4297. var sqw = qw * qw;
  4298. var sqz = qz * qz;
  4299. var sqx = qx * qx;
  4300. var sqy = qy * qy;
  4301. var zAxisY = qy * qz - qx * qw;
  4302. var limit = .4999999;
  4303. if (zAxisY < -limit) {
  4304. result.y = 2 * Math.atan2(qy, qw);
  4305. result.x = Math.PI / 2;
  4306. result.z = 0;
  4307. }
  4308. else if (zAxisY > limit) {
  4309. result.y = 2 * Math.atan2(qy, qw);
  4310. result.x = -Math.PI / 2;
  4311. result.z = 0;
  4312. }
  4313. else {
  4314. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4315. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4316. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4317. }
  4318. return this;
  4319. };
  4320. /**
  4321. * Updates the passed rotation matrix with the current Quaternion values.
  4322. * Returns the current Quaternion.
  4323. */
  4324. Quaternion.prototype.toRotationMatrix = function (result) {
  4325. var xx = this.x * this.x;
  4326. var yy = this.y * this.y;
  4327. var zz = this.z * this.z;
  4328. var xy = this.x * this.y;
  4329. var zw = this.z * this.w;
  4330. var zx = this.z * this.x;
  4331. var yw = this.y * this.w;
  4332. var yz = this.y * this.z;
  4333. var xw = this.x * this.w;
  4334. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4335. result.m[1] = 2.0 * (xy + zw);
  4336. result.m[2] = 2.0 * (zx - yw);
  4337. result.m[3] = 0;
  4338. result.m[4] = 2.0 * (xy - zw);
  4339. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4340. result.m[6] = 2.0 * (yz + xw);
  4341. result.m[7] = 0;
  4342. result.m[8] = 2.0 * (zx + yw);
  4343. result.m[9] = 2.0 * (yz - xw);
  4344. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4345. result.m[11] = 0;
  4346. result.m[12] = 0;
  4347. result.m[13] = 0;
  4348. result.m[14] = 0;
  4349. result.m[15] = 1.0;
  4350. result._markAsUpdated();
  4351. return this;
  4352. };
  4353. /**
  4354. * Updates the current Quaternion from the passed rotation matrix values.
  4355. * Returns the updated Quaternion.
  4356. */
  4357. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4358. Quaternion.FromRotationMatrixToRef(matrix, this);
  4359. return this;
  4360. };
  4361. // Statics
  4362. /**
  4363. * Returns a new Quaternion set from the passed rotation matrix values.
  4364. */
  4365. Quaternion.FromRotationMatrix = function (matrix) {
  4366. var result = new Quaternion();
  4367. Quaternion.FromRotationMatrixToRef(matrix, result);
  4368. return result;
  4369. };
  4370. /**
  4371. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4372. */
  4373. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4374. var data = matrix.m;
  4375. var m11 = data[0], m12 = data[4], m13 = data[8];
  4376. var m21 = data[1], m22 = data[5], m23 = data[9];
  4377. var m31 = data[2], m32 = data[6], m33 = data[10];
  4378. var trace = m11 + m22 + m33;
  4379. var s;
  4380. if (trace > 0) {
  4381. s = 0.5 / Math.sqrt(trace + 1.0);
  4382. result.w = 0.25 / s;
  4383. result.x = (m32 - m23) * s;
  4384. result.y = (m13 - m31) * s;
  4385. result.z = (m21 - m12) * s;
  4386. }
  4387. else if (m11 > m22 && m11 > m33) {
  4388. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4389. result.w = (m32 - m23) / s;
  4390. result.x = 0.25 * s;
  4391. result.y = (m12 + m21) / s;
  4392. result.z = (m13 + m31) / s;
  4393. }
  4394. else if (m22 > m33) {
  4395. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4396. result.w = (m13 - m31) / s;
  4397. result.x = (m12 + m21) / s;
  4398. result.y = 0.25 * s;
  4399. result.z = (m23 + m32) / s;
  4400. }
  4401. else {
  4402. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4403. result.w = (m21 - m12) / s;
  4404. result.x = (m13 + m31) / s;
  4405. result.y = (m23 + m32) / s;
  4406. result.z = 0.25 * s;
  4407. }
  4408. };
  4409. /**
  4410. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4411. */
  4412. Quaternion.Zero = function () {
  4413. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4414. };
  4415. /**
  4416. * Returns a new Quaternion as the inverted current Quaternion.
  4417. */
  4418. Quaternion.Inverse = function (q) {
  4419. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4420. };
  4421. /**
  4422. * Returns the identity Quaternion.
  4423. */
  4424. Quaternion.Identity = function () {
  4425. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4426. };
  4427. Quaternion.IsIdentity = function (quaternion) {
  4428. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4429. };
  4430. /**
  4431. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4432. */
  4433. Quaternion.RotationAxis = function (axis, angle) {
  4434. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4435. };
  4436. /**
  4437. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4438. */
  4439. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4440. var sin = Math.sin(angle / 2);
  4441. axis.normalize();
  4442. result.w = Math.cos(angle / 2);
  4443. result.x = axis.x * sin;
  4444. result.y = axis.y * sin;
  4445. result.z = axis.z * sin;
  4446. return result;
  4447. };
  4448. /**
  4449. * Retuns a new Quaternion set from the starting index of the passed array.
  4450. */
  4451. Quaternion.FromArray = function (array, offset) {
  4452. if (!offset) {
  4453. offset = 0;
  4454. }
  4455. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4456. };
  4457. /**
  4458. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4459. */
  4460. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4461. var q = new Quaternion();
  4462. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4463. return q;
  4464. };
  4465. /**
  4466. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4467. */
  4468. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4469. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4470. var halfRoll = roll * 0.5;
  4471. var halfPitch = pitch * 0.5;
  4472. var halfYaw = yaw * 0.5;
  4473. var sinRoll = Math.sin(halfRoll);
  4474. var cosRoll = Math.cos(halfRoll);
  4475. var sinPitch = Math.sin(halfPitch);
  4476. var cosPitch = Math.cos(halfPitch);
  4477. var sinYaw = Math.sin(halfYaw);
  4478. var cosYaw = Math.cos(halfYaw);
  4479. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4480. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4481. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4482. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4483. };
  4484. /**
  4485. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4486. */
  4487. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4488. var result = new Quaternion();
  4489. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4490. return result;
  4491. };
  4492. /**
  4493. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4494. */
  4495. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4496. // Produces a quaternion from Euler angles in the z-x-z orientation
  4497. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4498. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4499. var halfBeta = beta * 0.5;
  4500. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4501. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4502. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4503. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4504. };
  4505. /**
  4506. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4507. * cf to Vector3.RotationFromAxis() documentation.
  4508. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4509. */
  4510. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4511. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4512. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4513. return quat;
  4514. };
  4515. /**
  4516. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4517. * cf to Vector3.RotationFromAxis() documentation.
  4518. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4519. */
  4520. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4521. var rotMat = MathTmp.Matrix[0];
  4522. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4523. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4524. };
  4525. Quaternion.Slerp = function (left, right, amount) {
  4526. var result = Quaternion.Identity();
  4527. Quaternion.SlerpToRef(left, right, amount, result);
  4528. return result;
  4529. };
  4530. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4531. var num2;
  4532. var num3;
  4533. var num = amount;
  4534. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4535. var flag = false;
  4536. if (num4 < 0) {
  4537. flag = true;
  4538. num4 = -num4;
  4539. }
  4540. if (num4 > 0.999999) {
  4541. num3 = 1 - num;
  4542. num2 = flag ? -num : num;
  4543. }
  4544. else {
  4545. var num5 = Math.acos(num4);
  4546. var num6 = (1.0 / Math.sin(num5));
  4547. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4548. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4549. }
  4550. result.x = (num3 * left.x) + (num2 * right.x);
  4551. result.y = (num3 * left.y) + (num2 * right.y);
  4552. result.z = (num3 * left.z) + (num2 * right.z);
  4553. result.w = (num3 * left.w) + (num2 * right.w);
  4554. };
  4555. /**
  4556. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4557. */
  4558. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4559. var squared = amount * amount;
  4560. var cubed = amount * squared;
  4561. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4562. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4563. var part3 = (cubed - (2.0 * squared)) + amount;
  4564. var part4 = cubed - squared;
  4565. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4566. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4567. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4568. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4569. return new Quaternion(x, y, z, w);
  4570. };
  4571. return Quaternion;
  4572. }());
  4573. BABYLON.Quaternion = Quaternion;
  4574. var Matrix = /** @class */ (function () {
  4575. function Matrix() {
  4576. this._isIdentity = false;
  4577. this._isIdentityDirty = true;
  4578. this.m = new Float32Array(16);
  4579. this._markAsUpdated();
  4580. }
  4581. Matrix.prototype._markAsUpdated = function () {
  4582. this.updateFlag = Matrix._updateFlagSeed++;
  4583. this._isIdentityDirty = true;
  4584. };
  4585. // Properties
  4586. /**
  4587. * Boolean : True is the matrix is the identity matrix
  4588. */
  4589. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4590. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4591. if (this._isIdentityDirty) {
  4592. this._isIdentityDirty = false;
  4593. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4594. this._isIdentity = false;
  4595. }
  4596. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4597. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4598. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4599. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4600. this._isIdentity = false;
  4601. }
  4602. else {
  4603. this._isIdentity = true;
  4604. }
  4605. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4606. this._isIdentity = false;
  4607. }
  4608. }
  4609. return this._isIdentity;
  4610. };
  4611. /**
  4612. * Returns the matrix determinant (float).
  4613. */
  4614. Matrix.prototype.determinant = function () {
  4615. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4616. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4617. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4618. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4619. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4620. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4621. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4622. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4623. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4624. };
  4625. // Methods
  4626. /**
  4627. * Returns the matrix underlying array.
  4628. */
  4629. Matrix.prototype.toArray = function () {
  4630. return this.m;
  4631. };
  4632. /**
  4633. * Returns the matrix underlying array.
  4634. */
  4635. Matrix.prototype.asArray = function () {
  4636. return this.toArray();
  4637. };
  4638. /**
  4639. * Inverts in place the Matrix.
  4640. * Returns the Matrix inverted.
  4641. */
  4642. Matrix.prototype.invert = function () {
  4643. this.invertToRef(this);
  4644. return this;
  4645. };
  4646. /**
  4647. * Sets all the matrix elements to zero.
  4648. * Returns the Matrix.
  4649. */
  4650. Matrix.prototype.reset = function () {
  4651. for (var index = 0; index < 16; index++) {
  4652. this.m[index] = 0.0;
  4653. }
  4654. this._markAsUpdated();
  4655. return this;
  4656. };
  4657. /**
  4658. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4659. */
  4660. Matrix.prototype.add = function (other) {
  4661. var result = new Matrix();
  4662. this.addToRef(other, result);
  4663. return result;
  4664. };
  4665. /**
  4666. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4667. * Returns the Matrix.
  4668. */
  4669. Matrix.prototype.addToRef = function (other, result) {
  4670. for (var index = 0; index < 16; index++) {
  4671. result.m[index] = this.m[index] + other.m[index];
  4672. }
  4673. result._markAsUpdated();
  4674. return this;
  4675. };
  4676. /**
  4677. * Adds in place the passed matrix to the current Matrix.
  4678. * Returns the updated Matrix.
  4679. */
  4680. Matrix.prototype.addToSelf = function (other) {
  4681. for (var index = 0; index < 16; index++) {
  4682. this.m[index] += other.m[index];
  4683. }
  4684. this._markAsUpdated();
  4685. return this;
  4686. };
  4687. /**
  4688. * Sets the passed matrix with the current inverted Matrix.
  4689. * Returns the unmodified current Matrix.
  4690. */
  4691. Matrix.prototype.invertToRef = function (other) {
  4692. var l1 = this.m[0];
  4693. var l2 = this.m[1];
  4694. var l3 = this.m[2];
  4695. var l4 = this.m[3];
  4696. var l5 = this.m[4];
  4697. var l6 = this.m[5];
  4698. var l7 = this.m[6];
  4699. var l8 = this.m[7];
  4700. var l9 = this.m[8];
  4701. var l10 = this.m[9];
  4702. var l11 = this.m[10];
  4703. var l12 = this.m[11];
  4704. var l13 = this.m[12];
  4705. var l14 = this.m[13];
  4706. var l15 = this.m[14];
  4707. var l16 = this.m[15];
  4708. var l17 = (l11 * l16) - (l12 * l15);
  4709. var l18 = (l10 * l16) - (l12 * l14);
  4710. var l19 = (l10 * l15) - (l11 * l14);
  4711. var l20 = (l9 * l16) - (l12 * l13);
  4712. var l21 = (l9 * l15) - (l11 * l13);
  4713. var l22 = (l9 * l14) - (l10 * l13);
  4714. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4715. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4716. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4717. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4718. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4719. var l28 = (l7 * l16) - (l8 * l15);
  4720. var l29 = (l6 * l16) - (l8 * l14);
  4721. var l30 = (l6 * l15) - (l7 * l14);
  4722. var l31 = (l5 * l16) - (l8 * l13);
  4723. var l32 = (l5 * l15) - (l7 * l13);
  4724. var l33 = (l5 * l14) - (l6 * l13);
  4725. var l34 = (l7 * l12) - (l8 * l11);
  4726. var l35 = (l6 * l12) - (l8 * l10);
  4727. var l36 = (l6 * l11) - (l7 * l10);
  4728. var l37 = (l5 * l12) - (l8 * l9);
  4729. var l38 = (l5 * l11) - (l7 * l9);
  4730. var l39 = (l5 * l10) - (l6 * l9);
  4731. other.m[0] = l23 * l27;
  4732. other.m[4] = l24 * l27;
  4733. other.m[8] = l25 * l27;
  4734. other.m[12] = l26 * l27;
  4735. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4736. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4737. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4738. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4739. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4740. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4741. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4742. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4743. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4744. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4745. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4746. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4747. other._markAsUpdated();
  4748. return this;
  4749. };
  4750. /**
  4751. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4752. * Returns the updated Matrix.
  4753. */
  4754. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4755. this.m[12] = x;
  4756. this.m[13] = y;
  4757. this.m[14] = z;
  4758. this._markAsUpdated();
  4759. return this;
  4760. };
  4761. /**
  4762. * Inserts the translation vector in the current Matrix.
  4763. * Returns the updated Matrix.
  4764. */
  4765. Matrix.prototype.setTranslation = function (vector3) {
  4766. this.m[12] = vector3.x;
  4767. this.m[13] = vector3.y;
  4768. this.m[14] = vector3.z;
  4769. this._markAsUpdated();
  4770. return this;
  4771. };
  4772. /**
  4773. * Returns a new Vector3 as the extracted translation from the Matrix.
  4774. */
  4775. Matrix.prototype.getTranslation = function () {
  4776. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4777. };
  4778. /**
  4779. * Fill a Vector3 with the extracted translation from the Matrix.
  4780. */
  4781. Matrix.prototype.getTranslationToRef = function (result) {
  4782. result.x = this.m[12];
  4783. result.y = this.m[13];
  4784. result.z = this.m[14];
  4785. return this;
  4786. };
  4787. /**
  4788. * Remove rotation and scaling part from the Matrix.
  4789. * Returns the updated Matrix.
  4790. */
  4791. Matrix.prototype.removeRotationAndScaling = function () {
  4792. this.setRowFromFloats(0, 1, 0, 0, 0);
  4793. this.setRowFromFloats(1, 0, 1, 0, 0);
  4794. this.setRowFromFloats(2, 0, 0, 1, 0);
  4795. return this;
  4796. };
  4797. /**
  4798. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4799. */
  4800. Matrix.prototype.multiply = function (other) {
  4801. var result = new Matrix();
  4802. this.multiplyToRef(other, result);
  4803. return result;
  4804. };
  4805. /**
  4806. * Updates the current Matrix from the passed one values.
  4807. * Returns the updated Matrix.
  4808. */
  4809. Matrix.prototype.copyFrom = function (other) {
  4810. for (var index = 0; index < 16; index++) {
  4811. this.m[index] = other.m[index];
  4812. }
  4813. this._markAsUpdated();
  4814. return this;
  4815. };
  4816. /**
  4817. * Populates the passed array from the starting index with the Matrix values.
  4818. * Returns the Matrix.
  4819. */
  4820. Matrix.prototype.copyToArray = function (array, offset) {
  4821. if (offset === void 0) { offset = 0; }
  4822. for (var index = 0; index < 16; index++) {
  4823. array[offset + index] = this.m[index];
  4824. }
  4825. return this;
  4826. };
  4827. /**
  4828. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4829. */
  4830. Matrix.prototype.multiplyToRef = function (other, result) {
  4831. this.multiplyToArray(other, result.m, 0);
  4832. result._markAsUpdated();
  4833. return this;
  4834. };
  4835. /**
  4836. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4837. */
  4838. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4839. var tm0 = this.m[0];
  4840. var tm1 = this.m[1];
  4841. var tm2 = this.m[2];
  4842. var tm3 = this.m[3];
  4843. var tm4 = this.m[4];
  4844. var tm5 = this.m[5];
  4845. var tm6 = this.m[6];
  4846. var tm7 = this.m[7];
  4847. var tm8 = this.m[8];
  4848. var tm9 = this.m[9];
  4849. var tm10 = this.m[10];
  4850. var tm11 = this.m[11];
  4851. var tm12 = this.m[12];
  4852. var tm13 = this.m[13];
  4853. var tm14 = this.m[14];
  4854. var tm15 = this.m[15];
  4855. var om0 = other.m[0];
  4856. var om1 = other.m[1];
  4857. var om2 = other.m[2];
  4858. var om3 = other.m[3];
  4859. var om4 = other.m[4];
  4860. var om5 = other.m[5];
  4861. var om6 = other.m[6];
  4862. var om7 = other.m[7];
  4863. var om8 = other.m[8];
  4864. var om9 = other.m[9];
  4865. var om10 = other.m[10];
  4866. var om11 = other.m[11];
  4867. var om12 = other.m[12];
  4868. var om13 = other.m[13];
  4869. var om14 = other.m[14];
  4870. var om15 = other.m[15];
  4871. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4872. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4873. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4874. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4875. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4876. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4877. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4878. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4879. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4880. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4881. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4882. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4883. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4884. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4885. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4886. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4887. return this;
  4888. };
  4889. /**
  4890. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4891. */
  4892. Matrix.prototype.equals = function (value) {
  4893. return value &&
  4894. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4895. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4896. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4897. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4898. };
  4899. /**
  4900. * Returns a new Matrix from the current Matrix.
  4901. */
  4902. Matrix.prototype.clone = function () {
  4903. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  4904. };
  4905. /**
  4906. * Returns the string "Matrix"
  4907. */
  4908. Matrix.prototype.getClassName = function () {
  4909. return "Matrix";
  4910. };
  4911. /**
  4912. * Returns the Matrix hash code.
  4913. */
  4914. Matrix.prototype.getHashCode = function () {
  4915. var hash = this.m[0] || 0;
  4916. for (var i = 1; i < 16; i++) {
  4917. hash = (hash * 397) ^ (this.m[i] || 0);
  4918. }
  4919. return hash;
  4920. };
  4921. /**
  4922. * Decomposes the current Matrix into :
  4923. * - a scale vector3 passed as a reference to update,
  4924. * - a rotation quaternion passed as a reference to update,
  4925. * - a translation vector3 passed as a reference to update.
  4926. * Returns the true if operation was successful.
  4927. */
  4928. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4929. translation.x = this.m[12];
  4930. translation.y = this.m[13];
  4931. translation.z = this.m[14];
  4932. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4933. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4934. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4935. if (this.determinant() <= 0) {
  4936. scale.y *= -1;
  4937. }
  4938. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4939. rotation.x = 0;
  4940. rotation.y = 0;
  4941. rotation.z = 0;
  4942. rotation.w = 1;
  4943. return false;
  4944. }
  4945. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  4946. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4947. return true;
  4948. };
  4949. /**
  4950. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4951. */
  4952. Matrix.prototype.getRotationMatrix = function () {
  4953. var result = Matrix.Identity();
  4954. this.getRotationMatrixToRef(result);
  4955. return result;
  4956. };
  4957. /**
  4958. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4959. * Returns the current Matrix.
  4960. */
  4961. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4962. var m = this.m;
  4963. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4964. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4965. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4966. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4967. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4968. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4969. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  4970. return this;
  4971. };
  4972. // Statics
  4973. /**
  4974. * Returns a new Matrix set from the starting index of the passed array.
  4975. */
  4976. Matrix.FromArray = function (array, offset) {
  4977. var result = new Matrix();
  4978. if (!offset) {
  4979. offset = 0;
  4980. }
  4981. Matrix.FromArrayToRef(array, offset, result);
  4982. return result;
  4983. };
  4984. /**
  4985. * Sets the passed "result" matrix from the starting index of the passed array.
  4986. */
  4987. Matrix.FromArrayToRef = function (array, offset, result) {
  4988. for (var index = 0; index < 16; index++) {
  4989. result.m[index] = array[index + offset];
  4990. }
  4991. result._markAsUpdated();
  4992. };
  4993. /**
  4994. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  4995. */
  4996. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  4997. for (var index = 0; index < 16; index++) {
  4998. result.m[index] = array[index + offset] * scale;
  4999. }
  5000. result._markAsUpdated();
  5001. };
  5002. /**
  5003. * Sets the passed matrix "result" with the 16 passed floats.
  5004. */
  5005. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5006. result.m[0] = initialM11;
  5007. result.m[1] = initialM12;
  5008. result.m[2] = initialM13;
  5009. result.m[3] = initialM14;
  5010. result.m[4] = initialM21;
  5011. result.m[5] = initialM22;
  5012. result.m[6] = initialM23;
  5013. result.m[7] = initialM24;
  5014. result.m[8] = initialM31;
  5015. result.m[9] = initialM32;
  5016. result.m[10] = initialM33;
  5017. result.m[11] = initialM34;
  5018. result.m[12] = initialM41;
  5019. result.m[13] = initialM42;
  5020. result.m[14] = initialM43;
  5021. result.m[15] = initialM44;
  5022. result._markAsUpdated();
  5023. };
  5024. /**
  5025. * Returns the index-th row of the current matrix as a new Vector4.
  5026. */
  5027. Matrix.prototype.getRow = function (index) {
  5028. if (index < 0 || index > 3) {
  5029. return null;
  5030. }
  5031. var i = index * 4;
  5032. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5033. };
  5034. /**
  5035. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5036. * Returns the updated Matrix.
  5037. */
  5038. Matrix.prototype.setRow = function (index, row) {
  5039. if (index < 0 || index > 3) {
  5040. return this;
  5041. }
  5042. var i = index * 4;
  5043. this.m[i + 0] = row.x;
  5044. this.m[i + 1] = row.y;
  5045. this.m[i + 2] = row.z;
  5046. this.m[i + 3] = row.w;
  5047. this._markAsUpdated();
  5048. return this;
  5049. };
  5050. /**
  5051. * Compute the transpose of the matrix.
  5052. * Returns a new Matrix.
  5053. */
  5054. Matrix.prototype.transpose = function () {
  5055. return Matrix.Transpose(this);
  5056. };
  5057. /**
  5058. * Compute the transpose of the matrix.
  5059. * Returns the current matrix.
  5060. */
  5061. Matrix.prototype.transposeToRef = function (result) {
  5062. Matrix.TransposeToRef(this, result);
  5063. return this;
  5064. };
  5065. /**
  5066. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5067. * Returns the updated Matrix.
  5068. */
  5069. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5070. if (index < 0 || index > 3) {
  5071. return this;
  5072. }
  5073. var i = index * 4;
  5074. this.m[i + 0] = x;
  5075. this.m[i + 1] = y;
  5076. this.m[i + 2] = z;
  5077. this.m[i + 3] = w;
  5078. this._markAsUpdated();
  5079. return this;
  5080. };
  5081. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5082. /**
  5083. * Static identity matrix to be used as readonly matrix
  5084. * Must not be updated.
  5085. */
  5086. get: function () {
  5087. return Matrix._identityReadOnly;
  5088. },
  5089. enumerable: true,
  5090. configurable: true
  5091. });
  5092. /**
  5093. * Returns a new Matrix set from the 16 passed floats.
  5094. */
  5095. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5096. var result = new Matrix();
  5097. result.m[0] = initialM11;
  5098. result.m[1] = initialM12;
  5099. result.m[2] = initialM13;
  5100. result.m[3] = initialM14;
  5101. result.m[4] = initialM21;
  5102. result.m[5] = initialM22;
  5103. result.m[6] = initialM23;
  5104. result.m[7] = initialM24;
  5105. result.m[8] = initialM31;
  5106. result.m[9] = initialM32;
  5107. result.m[10] = initialM33;
  5108. result.m[11] = initialM34;
  5109. result.m[12] = initialM41;
  5110. result.m[13] = initialM42;
  5111. result.m[14] = initialM43;
  5112. result.m[15] = initialM44;
  5113. return result;
  5114. };
  5115. /**
  5116. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5117. */
  5118. Matrix.Compose = function (scale, rotation, translation) {
  5119. var result = Matrix.Identity();
  5120. Matrix.ComposeToRef(scale, rotation, translation, result);
  5121. return result;
  5122. };
  5123. /**
  5124. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5125. */
  5126. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5127. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5128. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5129. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5130. result.setTranslation(translation);
  5131. };
  5132. /**
  5133. * Returns a new indentity Matrix.
  5134. */
  5135. Matrix.Identity = function () {
  5136. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  5137. };
  5138. /**
  5139. * Sets the passed "result" as an identity matrix.
  5140. */
  5141. Matrix.IdentityToRef = function (result) {
  5142. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  5143. };
  5144. /**
  5145. * Returns a new zero Matrix.
  5146. */
  5147. Matrix.Zero = function () {
  5148. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  5149. };
  5150. /**
  5151. * Returns a new rotation matrix for "angle" radians around the X axis.
  5152. */
  5153. Matrix.RotationX = function (angle) {
  5154. var result = new Matrix();
  5155. Matrix.RotationXToRef(angle, result);
  5156. return result;
  5157. };
  5158. /**
  5159. * Returns a new Matrix as the passed inverted one.
  5160. */
  5161. Matrix.Invert = function (source) {
  5162. var result = new Matrix();
  5163. source.invertToRef(result);
  5164. return result;
  5165. };
  5166. /**
  5167. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5168. */
  5169. Matrix.RotationXToRef = function (angle, result) {
  5170. var s = Math.sin(angle);
  5171. var c = Math.cos(angle);
  5172. result.m[0] = 1.0;
  5173. result.m[15] = 1.0;
  5174. result.m[5] = c;
  5175. result.m[10] = c;
  5176. result.m[9] = -s;
  5177. result.m[6] = s;
  5178. result.m[1] = 0.0;
  5179. result.m[2] = 0.0;
  5180. result.m[3] = 0.0;
  5181. result.m[4] = 0.0;
  5182. result.m[7] = 0.0;
  5183. result.m[8] = 0.0;
  5184. result.m[11] = 0.0;
  5185. result.m[12] = 0.0;
  5186. result.m[13] = 0.0;
  5187. result.m[14] = 0.0;
  5188. result._markAsUpdated();
  5189. };
  5190. /**
  5191. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5192. */
  5193. Matrix.RotationY = function (angle) {
  5194. var result = new Matrix();
  5195. Matrix.RotationYToRef(angle, result);
  5196. return result;
  5197. };
  5198. /**
  5199. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5200. */
  5201. Matrix.RotationYToRef = function (angle, result) {
  5202. var s = Math.sin(angle);
  5203. var c = Math.cos(angle);
  5204. result.m[5] = 1.0;
  5205. result.m[15] = 1.0;
  5206. result.m[0] = c;
  5207. result.m[2] = -s;
  5208. result.m[8] = s;
  5209. result.m[10] = c;
  5210. result.m[1] = 0.0;
  5211. result.m[3] = 0.0;
  5212. result.m[4] = 0.0;
  5213. result.m[6] = 0.0;
  5214. result.m[7] = 0.0;
  5215. result.m[9] = 0.0;
  5216. result.m[11] = 0.0;
  5217. result.m[12] = 0.0;
  5218. result.m[13] = 0.0;
  5219. result.m[14] = 0.0;
  5220. result._markAsUpdated();
  5221. };
  5222. /**
  5223. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5224. */
  5225. Matrix.RotationZ = function (angle) {
  5226. var result = new Matrix();
  5227. Matrix.RotationZToRef(angle, result);
  5228. return result;
  5229. };
  5230. /**
  5231. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5232. */
  5233. Matrix.RotationZToRef = function (angle, result) {
  5234. var s = Math.sin(angle);
  5235. var c = Math.cos(angle);
  5236. result.m[10] = 1.0;
  5237. result.m[15] = 1.0;
  5238. result.m[0] = c;
  5239. result.m[1] = s;
  5240. result.m[4] = -s;
  5241. result.m[5] = c;
  5242. result.m[2] = 0.0;
  5243. result.m[3] = 0.0;
  5244. result.m[6] = 0.0;
  5245. result.m[7] = 0.0;
  5246. result.m[8] = 0.0;
  5247. result.m[9] = 0.0;
  5248. result.m[11] = 0.0;
  5249. result.m[12] = 0.0;
  5250. result.m[13] = 0.0;
  5251. result.m[14] = 0.0;
  5252. result._markAsUpdated();
  5253. };
  5254. /**
  5255. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5256. */
  5257. Matrix.RotationAxis = function (axis, angle) {
  5258. var result = Matrix.Zero();
  5259. Matrix.RotationAxisToRef(axis, angle, result);
  5260. return result;
  5261. };
  5262. /**
  5263. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5264. */
  5265. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5266. var s = Math.sin(-angle);
  5267. var c = Math.cos(-angle);
  5268. var c1 = 1 - c;
  5269. axis.normalize();
  5270. result.m[0] = (axis.x * axis.x) * c1 + c;
  5271. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5272. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5273. result.m[3] = 0.0;
  5274. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5275. result.m[5] = (axis.y * axis.y) * c1 + c;
  5276. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5277. result.m[7] = 0.0;
  5278. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5279. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5280. result.m[10] = (axis.z * axis.z) * c1 + c;
  5281. result.m[11] = 0.0;
  5282. result.m[15] = 1.0;
  5283. result._markAsUpdated();
  5284. };
  5285. /**
  5286. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5287. */
  5288. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5289. var result = new Matrix();
  5290. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5291. return result;
  5292. };
  5293. /**
  5294. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5295. */
  5296. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5297. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5298. this._tempQuaternion.toRotationMatrix(result);
  5299. };
  5300. /**
  5301. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5302. */
  5303. Matrix.Scaling = function (x, y, z) {
  5304. var result = Matrix.Zero();
  5305. Matrix.ScalingToRef(x, y, z, result);
  5306. return result;
  5307. };
  5308. /**
  5309. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5310. */
  5311. Matrix.ScalingToRef = function (x, y, z, result) {
  5312. result.m[0] = x;
  5313. result.m[1] = 0.0;
  5314. result.m[2] = 0.0;
  5315. result.m[3] = 0.0;
  5316. result.m[4] = 0.0;
  5317. result.m[5] = y;
  5318. result.m[6] = 0.0;
  5319. result.m[7] = 0.0;
  5320. result.m[8] = 0.0;
  5321. result.m[9] = 0.0;
  5322. result.m[10] = z;
  5323. result.m[11] = 0.0;
  5324. result.m[12] = 0.0;
  5325. result.m[13] = 0.0;
  5326. result.m[14] = 0.0;
  5327. result.m[15] = 1.0;
  5328. result._markAsUpdated();
  5329. };
  5330. /**
  5331. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5332. */
  5333. Matrix.Translation = function (x, y, z) {
  5334. var result = Matrix.Identity();
  5335. Matrix.TranslationToRef(x, y, z, result);
  5336. return result;
  5337. };
  5338. /**
  5339. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5340. */
  5341. Matrix.TranslationToRef = function (x, y, z, result) {
  5342. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  5343. };
  5344. /**
  5345. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  5346. */
  5347. Matrix.Lerp = function (startValue, endValue, gradient) {
  5348. var result = Matrix.Zero();
  5349. for (var index = 0; index < 16; index++) {
  5350. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5351. }
  5352. result._markAsUpdated();
  5353. return result;
  5354. };
  5355. /**
  5356. * Returns a new Matrix whose values are computed by :
  5357. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5358. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5359. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5360. */
  5361. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5362. var startScale = new Vector3(0, 0, 0);
  5363. var startRotation = new Quaternion();
  5364. var startTranslation = new Vector3(0, 0, 0);
  5365. startValue.decompose(startScale, startRotation, startTranslation);
  5366. var endScale = new Vector3(0, 0, 0);
  5367. var endRotation = new Quaternion();
  5368. var endTranslation = new Vector3(0, 0, 0);
  5369. endValue.decompose(endScale, endRotation, endTranslation);
  5370. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5371. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5372. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5373. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5374. };
  5375. /**
  5376. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5377. * This methods works for a Left-Handed system.
  5378. */
  5379. Matrix.LookAtLH = function (eye, target, up) {
  5380. var result = Matrix.Zero();
  5381. Matrix.LookAtLHToRef(eye, target, up, result);
  5382. return result;
  5383. };
  5384. /**
  5385. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5386. * This methods works for a Left-Handed system.
  5387. */
  5388. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5389. // Z axis
  5390. target.subtractToRef(eye, this._zAxis);
  5391. this._zAxis.normalize();
  5392. // X axis
  5393. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5394. if (this._xAxis.lengthSquared() === 0) {
  5395. this._xAxis.x = 1.0;
  5396. }
  5397. else {
  5398. this._xAxis.normalize();
  5399. }
  5400. // Y axis
  5401. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5402. this._yAxis.normalize();
  5403. // Eye angles
  5404. var ex = -Vector3.Dot(this._xAxis, eye);
  5405. var ey = -Vector3.Dot(this._yAxis, eye);
  5406. var ez = -Vector3.Dot(this._zAxis, eye);
  5407. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  5408. };
  5409. /**
  5410. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5411. * This methods works for a Right-Handed system.
  5412. */
  5413. Matrix.LookAtRH = function (eye, target, up) {
  5414. var result = Matrix.Zero();
  5415. Matrix.LookAtRHToRef(eye, target, up, result);
  5416. return result;
  5417. };
  5418. /**
  5419. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5420. * This methods works for a Left-Handed system.
  5421. */
  5422. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5423. // Z axis
  5424. eye.subtractToRef(target, this._zAxis);
  5425. this._zAxis.normalize();
  5426. // X axis
  5427. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5428. if (this._xAxis.lengthSquared() === 0) {
  5429. this._xAxis.x = 1.0;
  5430. }
  5431. else {
  5432. this._xAxis.normalize();
  5433. }
  5434. // Y axis
  5435. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5436. this._yAxis.normalize();
  5437. // Eye angles
  5438. var ex = -Vector3.Dot(this._xAxis, eye);
  5439. var ey = -Vector3.Dot(this._yAxis, eye);
  5440. var ez = -Vector3.Dot(this._zAxis, eye);
  5441. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  5442. };
  5443. /**
  5444. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5445. */
  5446. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5447. var matrix = Matrix.Zero();
  5448. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5449. return matrix;
  5450. };
  5451. /**
  5452. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5453. */
  5454. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5455. var n = znear;
  5456. var f = zfar;
  5457. var a = 2.0 / width;
  5458. var b = 2.0 / height;
  5459. var c = 2.0 / (f - n);
  5460. var d = -(f + n) / (f - n);
  5461. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  5462. };
  5463. /**
  5464. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5465. */
  5466. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5467. var matrix = Matrix.Zero();
  5468. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5469. return matrix;
  5470. };
  5471. /**
  5472. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5473. */
  5474. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5475. var n = znear;
  5476. var f = zfar;
  5477. var a = 2.0 / (right - left);
  5478. var b = 2.0 / (top - bottom);
  5479. var c = 2.0 / (f - n);
  5480. var d = -(f + n) / (f - n);
  5481. var i0 = (left + right) / (left - right);
  5482. var i1 = (top + bottom) / (bottom - top);
  5483. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  5484. };
  5485. /**
  5486. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5487. */
  5488. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5489. var matrix = Matrix.Zero();
  5490. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5491. return matrix;
  5492. };
  5493. /**
  5494. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5495. */
  5496. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5497. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5498. result.m[10] *= -1.0;
  5499. };
  5500. /**
  5501. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5502. */
  5503. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5504. var matrix = Matrix.Zero();
  5505. var n = znear;
  5506. var f = zfar;
  5507. var a = 2.0 * n / width;
  5508. var b = 2.0 * n / height;
  5509. var c = (f + n) / (f - n);
  5510. var d = -2.0 * f * n / (f - n);
  5511. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  5512. return matrix;
  5513. };
  5514. /**
  5515. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5516. */
  5517. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5518. var matrix = Matrix.Zero();
  5519. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5520. return matrix;
  5521. };
  5522. /**
  5523. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5524. */
  5525. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5526. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5527. var n = znear;
  5528. var f = zfar;
  5529. var t = 1.0 / (Math.tan(fov * 0.5));
  5530. var a = isVerticalFovFixed ? (t / aspect) : t;
  5531. var b = isVerticalFovFixed ? t : (t * aspect);
  5532. var c = (f + n) / (f - n);
  5533. var d = -2.0 * f * n / (f - n);
  5534. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  5535. };
  5536. /**
  5537. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5538. */
  5539. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5540. var matrix = Matrix.Zero();
  5541. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5542. return matrix;
  5543. };
  5544. /**
  5545. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5546. */
  5547. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5548. //alternatively this could be expressed as:
  5549. // m = PerspectiveFovLHToRef
  5550. // m[10] *= -1.0;
  5551. // m[11] *= -1.0;
  5552. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5553. var n = znear;
  5554. var f = zfar;
  5555. var t = 1.0 / (Math.tan(fov * 0.5));
  5556. var a = isVerticalFovFixed ? (t / aspect) : t;
  5557. var b = isVerticalFovFixed ? t : (t * aspect);
  5558. var c = -(f + n) / (f - n);
  5559. var d = -2 * f * n / (f - n);
  5560. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  5561. };
  5562. /**
  5563. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5564. */
  5565. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5566. if (rightHanded === void 0) { rightHanded = false; }
  5567. var rightHandedFactor = rightHanded ? -1 : 1;
  5568. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5569. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5570. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5571. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5572. var xScale = 2.0 / (leftTan + rightTan);
  5573. var yScale = 2.0 / (upTan + downTan);
  5574. result.m[0] = xScale;
  5575. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5576. result.m[5] = yScale;
  5577. result.m[6] = result.m[7] = 0.0;
  5578. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5579. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5580. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5581. result.m[10] = -zfar / (znear - zfar);
  5582. result.m[11] = 1.0 * rightHandedFactor;
  5583. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5584. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5585. // result.m[14] = (znear * zfar) / (znear - zfar);
  5586. result._markAsUpdated();
  5587. };
  5588. /**
  5589. * Returns the final transformation matrix : world * view * projection * viewport
  5590. */
  5591. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5592. var cw = viewport.width;
  5593. var ch = viewport.height;
  5594. var cx = viewport.x;
  5595. var cy = viewport.y;
  5596. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  5597. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5598. };
  5599. /**
  5600. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5601. */
  5602. Matrix.GetAsMatrix2x2 = function (matrix) {
  5603. return new Float32Array([
  5604. matrix.m[0], matrix.m[1],
  5605. matrix.m[4], matrix.m[5]
  5606. ]);
  5607. };
  5608. /**
  5609. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5610. */
  5611. Matrix.GetAsMatrix3x3 = function (matrix) {
  5612. return new Float32Array([
  5613. matrix.m[0], matrix.m[1], matrix.m[2],
  5614. matrix.m[4], matrix.m[5], matrix.m[6],
  5615. matrix.m[8], matrix.m[9], matrix.m[10]
  5616. ]);
  5617. };
  5618. /**
  5619. * Compute the transpose of the passed Matrix.
  5620. * Returns a new Matrix.
  5621. */
  5622. Matrix.Transpose = function (matrix) {
  5623. var result = new Matrix();
  5624. Matrix.TransposeToRef(matrix, result);
  5625. return result;
  5626. };
  5627. /**
  5628. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5629. */
  5630. Matrix.TransposeToRef = function (matrix, result) {
  5631. result.m[0] = matrix.m[0];
  5632. result.m[1] = matrix.m[4];
  5633. result.m[2] = matrix.m[8];
  5634. result.m[3] = matrix.m[12];
  5635. result.m[4] = matrix.m[1];
  5636. result.m[5] = matrix.m[5];
  5637. result.m[6] = matrix.m[9];
  5638. result.m[7] = matrix.m[13];
  5639. result.m[8] = matrix.m[2];
  5640. result.m[9] = matrix.m[6];
  5641. result.m[10] = matrix.m[10];
  5642. result.m[11] = matrix.m[14];
  5643. result.m[12] = matrix.m[3];
  5644. result.m[13] = matrix.m[7];
  5645. result.m[14] = matrix.m[11];
  5646. result.m[15] = matrix.m[15];
  5647. };
  5648. /**
  5649. * Returns a new Matrix as the reflection matrix across the passed plane.
  5650. */
  5651. Matrix.Reflection = function (plane) {
  5652. var matrix = new Matrix();
  5653. Matrix.ReflectionToRef(plane, matrix);
  5654. return matrix;
  5655. };
  5656. /**
  5657. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5658. */
  5659. Matrix.ReflectionToRef = function (plane, result) {
  5660. plane.normalize();
  5661. var x = plane.normal.x;
  5662. var y = plane.normal.y;
  5663. var z = plane.normal.z;
  5664. var temp = -2 * x;
  5665. var temp2 = -2 * y;
  5666. var temp3 = -2 * z;
  5667. result.m[0] = (temp * x) + 1;
  5668. result.m[1] = temp2 * x;
  5669. result.m[2] = temp3 * x;
  5670. result.m[3] = 0.0;
  5671. result.m[4] = temp * y;
  5672. result.m[5] = (temp2 * y) + 1;
  5673. result.m[6] = temp3 * y;
  5674. result.m[7] = 0.0;
  5675. result.m[8] = temp * z;
  5676. result.m[9] = temp2 * z;
  5677. result.m[10] = (temp3 * z) + 1;
  5678. result.m[11] = 0.0;
  5679. result.m[12] = temp * plane.d;
  5680. result.m[13] = temp2 * plane.d;
  5681. result.m[14] = temp3 * plane.d;
  5682. result.m[15] = 1.0;
  5683. result._markAsUpdated();
  5684. };
  5685. /**
  5686. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5687. */
  5688. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5689. result.m[0] = xaxis.x;
  5690. result.m[1] = xaxis.y;
  5691. result.m[2] = xaxis.z;
  5692. result.m[3] = 0.0;
  5693. result.m[4] = yaxis.x;
  5694. result.m[5] = yaxis.y;
  5695. result.m[6] = yaxis.z;
  5696. result.m[7] = 0.0;
  5697. result.m[8] = zaxis.x;
  5698. result.m[9] = zaxis.y;
  5699. result.m[10] = zaxis.z;
  5700. result.m[11] = 0.0;
  5701. result.m[12] = 0.0;
  5702. result.m[13] = 0.0;
  5703. result.m[14] = 0.0;
  5704. result.m[15] = 1.0;
  5705. result._markAsUpdated();
  5706. };
  5707. /**
  5708. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5709. */
  5710. Matrix.FromQuaternionToRef = function (quat, result) {
  5711. var xx = quat.x * quat.x;
  5712. var yy = quat.y * quat.y;
  5713. var zz = quat.z * quat.z;
  5714. var xy = quat.x * quat.y;
  5715. var zw = quat.z * quat.w;
  5716. var zx = quat.z * quat.x;
  5717. var yw = quat.y * quat.w;
  5718. var yz = quat.y * quat.z;
  5719. var xw = quat.x * quat.w;
  5720. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5721. result.m[1] = 2.0 * (xy + zw);
  5722. result.m[2] = 2.0 * (zx - yw);
  5723. result.m[3] = 0.0;
  5724. result.m[4] = 2.0 * (xy - zw);
  5725. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5726. result.m[6] = 2.0 * (yz + xw);
  5727. result.m[7] = 0.0;
  5728. result.m[8] = 2.0 * (zx + yw);
  5729. result.m[9] = 2.0 * (yz - xw);
  5730. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5731. result.m[11] = 0.0;
  5732. result.m[12] = 0.0;
  5733. result.m[13] = 0.0;
  5734. result.m[14] = 0.0;
  5735. result.m[15] = 1.0;
  5736. result._markAsUpdated();
  5737. };
  5738. Matrix._tempQuaternion = new Quaternion();
  5739. Matrix._xAxis = Vector3.Zero();
  5740. Matrix._yAxis = Vector3.Zero();
  5741. Matrix._zAxis = Vector3.Zero();
  5742. Matrix._updateFlagSeed = 0;
  5743. Matrix._identityReadOnly = Matrix.Identity();
  5744. return Matrix;
  5745. }());
  5746. BABYLON.Matrix = Matrix;
  5747. var Plane = /** @class */ (function () {
  5748. /**
  5749. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5750. */
  5751. function Plane(a, b, c, d) {
  5752. this.normal = new Vector3(a, b, c);
  5753. this.d = d;
  5754. }
  5755. /**
  5756. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5757. */
  5758. Plane.prototype.asArray = function () {
  5759. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5760. };
  5761. // Methods
  5762. /**
  5763. * Returns a new plane copied from the current Plane.
  5764. */
  5765. Plane.prototype.clone = function () {
  5766. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5767. };
  5768. /**
  5769. * Returns the string "Plane".
  5770. */
  5771. Plane.prototype.getClassName = function () {
  5772. return "Plane";
  5773. };
  5774. /**
  5775. * Returns the Plane hash code.
  5776. */
  5777. Plane.prototype.getHashCode = function () {
  5778. var hash = this.normal.getHashCode();
  5779. hash = (hash * 397) ^ (this.d || 0);
  5780. return hash;
  5781. };
  5782. /**
  5783. * Normalize the current Plane in place.
  5784. * Returns the updated Plane.
  5785. */
  5786. Plane.prototype.normalize = function () {
  5787. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5788. var magnitude = 0.0;
  5789. if (norm !== 0) {
  5790. magnitude = 1.0 / norm;
  5791. }
  5792. this.normal.x *= magnitude;
  5793. this.normal.y *= magnitude;
  5794. this.normal.z *= magnitude;
  5795. this.d *= magnitude;
  5796. return this;
  5797. };
  5798. /**
  5799. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5800. */
  5801. Plane.prototype.transform = function (transformation) {
  5802. var transposedMatrix = Matrix.Transpose(transformation);
  5803. var x = this.normal.x;
  5804. var y = this.normal.y;
  5805. var z = this.normal.z;
  5806. var d = this.d;
  5807. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5808. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5809. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5810. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5811. return new Plane(normalX, normalY, normalZ, finalD);
  5812. };
  5813. /**
  5814. * Returns the dot product (float) of the point coordinates and the plane normal.
  5815. */
  5816. Plane.prototype.dotCoordinate = function (point) {
  5817. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5818. };
  5819. /**
  5820. * Updates the current Plane from the plane defined by the three passed points.
  5821. * Returns the updated Plane.
  5822. */
  5823. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5824. var x1 = point2.x - point1.x;
  5825. var y1 = point2.y - point1.y;
  5826. var z1 = point2.z - point1.z;
  5827. var x2 = point3.x - point1.x;
  5828. var y2 = point3.y - point1.y;
  5829. var z2 = point3.z - point1.z;
  5830. var yz = (y1 * z2) - (z1 * y2);
  5831. var xz = (z1 * x2) - (x1 * z2);
  5832. var xy = (x1 * y2) - (y1 * x2);
  5833. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5834. var invPyth;
  5835. if (pyth !== 0) {
  5836. invPyth = 1.0 / pyth;
  5837. }
  5838. else {
  5839. invPyth = 0.0;
  5840. }
  5841. this.normal.x = yz * invPyth;
  5842. this.normal.y = xz * invPyth;
  5843. this.normal.z = xy * invPyth;
  5844. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5845. return this;
  5846. };
  5847. /**
  5848. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5849. */
  5850. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5851. var dot = Vector3.Dot(this.normal, direction);
  5852. return (dot <= epsilon);
  5853. };
  5854. /**
  5855. * Returns the signed distance (float) from the passed point to the Plane.
  5856. */
  5857. Plane.prototype.signedDistanceTo = function (point) {
  5858. return Vector3.Dot(point, this.normal) + this.d;
  5859. };
  5860. // Statics
  5861. /**
  5862. * Returns a new Plane from the passed array.
  5863. */
  5864. Plane.FromArray = function (array) {
  5865. return new Plane(array[0], array[1], array[2], array[3]);
  5866. };
  5867. /**
  5868. * Returns a new Plane defined by the three passed points.
  5869. */
  5870. Plane.FromPoints = function (point1, point2, point3) {
  5871. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5872. result.copyFromPoints(point1, point2, point3);
  5873. return result;
  5874. };
  5875. /**
  5876. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5877. * Note : the vector "normal" is updated because normalized.
  5878. */
  5879. Plane.FromPositionAndNormal = function (origin, normal) {
  5880. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5881. normal.normalize();
  5882. result.normal = normal;
  5883. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5884. return result;
  5885. };
  5886. /**
  5887. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5888. */
  5889. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5890. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5891. return Vector3.Dot(point, normal) + d;
  5892. };
  5893. return Plane;
  5894. }());
  5895. BABYLON.Plane = Plane;
  5896. var Viewport = /** @class */ (function () {
  5897. /**
  5898. * Creates a Viewport object located at (x, y) and sized (width, height).
  5899. */
  5900. function Viewport(x, y, width, height) {
  5901. this.x = x;
  5902. this.y = y;
  5903. this.width = width;
  5904. this.height = height;
  5905. }
  5906. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5907. if (renderWidthOrEngine.getRenderWidth) {
  5908. var engine = renderWidthOrEngine;
  5909. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5910. }
  5911. var renderWidth = renderWidthOrEngine;
  5912. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5913. };
  5914. /**
  5915. * Returns a new Viewport copied from the current one.
  5916. */
  5917. Viewport.prototype.clone = function () {
  5918. return new Viewport(this.x, this.y, this.width, this.height);
  5919. };
  5920. return Viewport;
  5921. }());
  5922. BABYLON.Viewport = Viewport;
  5923. var Frustum = /** @class */ (function () {
  5924. function Frustum() {
  5925. }
  5926. /**
  5927. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5928. */
  5929. Frustum.GetPlanes = function (transform) {
  5930. var frustumPlanes = [];
  5931. for (var index = 0; index < 6; index++) {
  5932. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5933. }
  5934. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5935. return frustumPlanes;
  5936. };
  5937. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5938. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5939. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5940. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5941. frustumPlane.d = transform.m[15] + transform.m[14];
  5942. frustumPlane.normalize();
  5943. };
  5944. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5945. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5946. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5947. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5948. frustumPlane.d = transform.m[15] - transform.m[14];
  5949. frustumPlane.normalize();
  5950. };
  5951. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5952. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5953. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5954. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5955. frustumPlane.d = transform.m[15] + transform.m[12];
  5956. frustumPlane.normalize();
  5957. };
  5958. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5959. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5960. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5961. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5962. frustumPlane.d = transform.m[15] - transform.m[12];
  5963. frustumPlane.normalize();
  5964. };
  5965. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5966. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5967. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5968. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5969. frustumPlane.d = transform.m[15] - transform.m[13];
  5970. frustumPlane.normalize();
  5971. };
  5972. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5973. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5974. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5975. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5976. frustumPlane.d = transform.m[15] + transform.m[13];
  5977. frustumPlane.normalize();
  5978. };
  5979. /**
  5980. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5981. */
  5982. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5983. // Near
  5984. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5985. // Far
  5986. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  5987. // Left
  5988. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  5989. // Right
  5990. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  5991. // Top
  5992. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  5993. // Bottom
  5994. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  5995. };
  5996. return Frustum;
  5997. }());
  5998. BABYLON.Frustum = Frustum;
  5999. var Space;
  6000. (function (Space) {
  6001. Space[Space["LOCAL"] = 0] = "LOCAL";
  6002. Space[Space["WORLD"] = 1] = "WORLD";
  6003. Space[Space["BONE"] = 2] = "BONE";
  6004. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6005. var Axis = /** @class */ (function () {
  6006. function Axis() {
  6007. }
  6008. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6009. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6010. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6011. return Axis;
  6012. }());
  6013. BABYLON.Axis = Axis;
  6014. ;
  6015. var BezierCurve = /** @class */ (function () {
  6016. function BezierCurve() {
  6017. }
  6018. /**
  6019. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6020. */
  6021. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6022. // Extract X (which is equal to time here)
  6023. var f0 = 1 - 3 * x2 + 3 * x1;
  6024. var f1 = 3 * x2 - 6 * x1;
  6025. var f2 = 3 * x1;
  6026. var refinedT = t;
  6027. for (var i = 0; i < 5; i++) {
  6028. var refinedT2 = refinedT * refinedT;
  6029. var refinedT3 = refinedT2 * refinedT;
  6030. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6031. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6032. refinedT -= (x - t) * slope;
  6033. refinedT = Math.min(1, Math.max(0, refinedT));
  6034. }
  6035. // Resolve cubic bezier for the given x
  6036. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6037. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6038. Math.pow(refinedT, 3);
  6039. };
  6040. return BezierCurve;
  6041. }());
  6042. BABYLON.BezierCurve = BezierCurve;
  6043. var Orientation;
  6044. (function (Orientation) {
  6045. Orientation[Orientation["CW"] = 0] = "CW";
  6046. Orientation[Orientation["CCW"] = 1] = "CCW";
  6047. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6048. var Angle = /** @class */ (function () {
  6049. /**
  6050. * Creates an Angle object of "radians" radians (float).
  6051. */
  6052. function Angle(radians) {
  6053. var _this = this;
  6054. /**
  6055. * Returns the Angle value in degrees (float).
  6056. */
  6057. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6058. /**
  6059. * Returns the Angle value in radians (float).
  6060. */
  6061. this.radians = function () { return _this._radians; };
  6062. this._radians = radians;
  6063. if (this._radians < 0.0)
  6064. this._radians += (2.0 * Math.PI);
  6065. }
  6066. /**
  6067. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6068. */
  6069. Angle.BetweenTwoPoints = function (a, b) {
  6070. var delta = b.subtract(a);
  6071. var theta = Math.atan2(delta.y, delta.x);
  6072. return new Angle(theta);
  6073. };
  6074. /**
  6075. * Returns a new Angle object from the passed float in radians.
  6076. */
  6077. Angle.FromRadians = function (radians) {
  6078. return new Angle(radians);
  6079. };
  6080. /**
  6081. * Returns a new Angle object from the passed float in degrees.
  6082. */
  6083. Angle.FromDegrees = function (degrees) {
  6084. return new Angle(degrees * Math.PI / 180.0);
  6085. };
  6086. return Angle;
  6087. }());
  6088. BABYLON.Angle = Angle;
  6089. var Arc2 = /** @class */ (function () {
  6090. /**
  6091. * Creates an Arc object from the three passed points : start, middle and end.
  6092. */
  6093. function Arc2(startPoint, midPoint, endPoint) {
  6094. this.startPoint = startPoint;
  6095. this.midPoint = midPoint;
  6096. this.endPoint = endPoint;
  6097. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6098. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6099. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6100. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6101. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  6102. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6103. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6104. var a1 = this.startAngle.degrees();
  6105. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6106. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6107. // angles correction
  6108. if (a2 - a1 > +180.0)
  6109. a2 -= 360.0;
  6110. if (a2 - a1 < -180.0)
  6111. a2 += 360.0;
  6112. if (a3 - a2 > +180.0)
  6113. a3 -= 360.0;
  6114. if (a3 - a2 < -180.0)
  6115. a3 += 360.0;
  6116. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6117. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6118. }
  6119. return Arc2;
  6120. }());
  6121. BABYLON.Arc2 = Arc2;
  6122. var Path2 = /** @class */ (function () {
  6123. /**
  6124. * Creates a Path2 object from the starting 2D coordinates x and y.
  6125. */
  6126. function Path2(x, y) {
  6127. this._points = new Array();
  6128. this._length = 0.0;
  6129. this.closed = false;
  6130. this._points.push(new Vector2(x, y));
  6131. }
  6132. /**
  6133. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6134. * Returns the updated Path2.
  6135. */
  6136. Path2.prototype.addLineTo = function (x, y) {
  6137. if (this.closed) {
  6138. //Tools.Error("cannot add lines to closed paths");
  6139. return this;
  6140. }
  6141. var newPoint = new Vector2(x, y);
  6142. var previousPoint = this._points[this._points.length - 1];
  6143. this._points.push(newPoint);
  6144. this._length += newPoint.subtract(previousPoint).length();
  6145. return this;
  6146. };
  6147. /**
  6148. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  6149. * Returns the updated Path2.
  6150. */
  6151. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6152. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6153. if (this.closed) {
  6154. //Tools.Error("cannot add arcs to closed paths");
  6155. return this;
  6156. }
  6157. var startPoint = this._points[this._points.length - 1];
  6158. var midPoint = new Vector2(midX, midY);
  6159. var endPoint = new Vector2(endX, endY);
  6160. var arc = new Arc2(startPoint, midPoint, endPoint);
  6161. var increment = arc.angle.radians() / numberOfSegments;
  6162. if (arc.orientation === Orientation.CW)
  6163. increment *= -1;
  6164. var currentAngle = arc.startAngle.radians() + increment;
  6165. for (var i = 0; i < numberOfSegments; i++) {
  6166. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6167. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6168. this.addLineTo(x, y);
  6169. currentAngle += increment;
  6170. }
  6171. return this;
  6172. };
  6173. /**
  6174. * Closes the Path2.
  6175. * Returns the Path2.
  6176. */
  6177. Path2.prototype.close = function () {
  6178. this.closed = true;
  6179. return this;
  6180. };
  6181. /**
  6182. * Returns the Path2 total length (float).
  6183. */
  6184. Path2.prototype.length = function () {
  6185. var result = this._length;
  6186. if (!this.closed) {
  6187. var lastPoint = this._points[this._points.length - 1];
  6188. var firstPoint = this._points[0];
  6189. result += (firstPoint.subtract(lastPoint).length());
  6190. }
  6191. return result;
  6192. };
  6193. /**
  6194. * Returns the Path2 internal array of points.
  6195. */
  6196. Path2.prototype.getPoints = function () {
  6197. return this._points;
  6198. };
  6199. /**
  6200. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6201. */
  6202. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6203. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6204. //Tools.Error("normalized length position should be between 0 and 1.");
  6205. return Vector2.Zero();
  6206. }
  6207. var lengthPosition = normalizedLengthPosition * this.length();
  6208. var previousOffset = 0;
  6209. for (var i = 0; i < this._points.length; i++) {
  6210. var j = (i + 1) % this._points.length;
  6211. var a = this._points[i];
  6212. var b = this._points[j];
  6213. var bToA = b.subtract(a);
  6214. var nextOffset = (bToA.length() + previousOffset);
  6215. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6216. var dir = bToA.normalize();
  6217. var localOffset = lengthPosition - previousOffset;
  6218. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6219. }
  6220. previousOffset = nextOffset;
  6221. }
  6222. //Tools.Error("internal error");
  6223. return Vector2.Zero();
  6224. };
  6225. /**
  6226. * Returns a new Path2 starting at the coordinates (x, y).
  6227. */
  6228. Path2.StartingAt = function (x, y) {
  6229. return new Path2(x, y);
  6230. };
  6231. return Path2;
  6232. }());
  6233. BABYLON.Path2 = Path2;
  6234. var Path3D = /** @class */ (function () {
  6235. /**
  6236. * new Path3D(path, normal, raw)
  6237. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6238. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6239. * path : an array of Vector3, the curve axis of the Path3D
  6240. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6241. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6242. */
  6243. function Path3D(path, firstNormal, raw) {
  6244. if (firstNormal === void 0) { firstNormal = null; }
  6245. this.path = path;
  6246. this._curve = new Array();
  6247. this._distances = new Array();
  6248. this._tangents = new Array();
  6249. this._normals = new Array();
  6250. this._binormals = new Array();
  6251. for (var p = 0; p < path.length; p++) {
  6252. this._curve[p] = path[p].clone(); // hard copy
  6253. }
  6254. this._raw = raw || false;
  6255. this._compute(firstNormal);
  6256. }
  6257. /**
  6258. * Returns the Path3D array of successive Vector3 designing its curve.
  6259. */
  6260. Path3D.prototype.getCurve = function () {
  6261. return this._curve;
  6262. };
  6263. /**
  6264. * Returns an array populated with tangent vectors on each Path3D curve point.
  6265. */
  6266. Path3D.prototype.getTangents = function () {
  6267. return this._tangents;
  6268. };
  6269. /**
  6270. * Returns an array populated with normal vectors on each Path3D curve point.
  6271. */
  6272. Path3D.prototype.getNormals = function () {
  6273. return this._normals;
  6274. };
  6275. /**
  6276. * Returns an array populated with binormal vectors on each Path3D curve point.
  6277. */
  6278. Path3D.prototype.getBinormals = function () {
  6279. return this._binormals;
  6280. };
  6281. /**
  6282. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6283. */
  6284. Path3D.prototype.getDistances = function () {
  6285. return this._distances;
  6286. };
  6287. /**
  6288. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6289. * Returns the same object updated.
  6290. */
  6291. Path3D.prototype.update = function (path, firstNormal) {
  6292. if (firstNormal === void 0) { firstNormal = null; }
  6293. for (var p = 0; p < path.length; p++) {
  6294. this._curve[p].x = path[p].x;
  6295. this._curve[p].y = path[p].y;
  6296. this._curve[p].z = path[p].z;
  6297. }
  6298. this._compute(firstNormal);
  6299. return this;
  6300. };
  6301. // private function compute() : computes tangents, normals and binormals
  6302. Path3D.prototype._compute = function (firstNormal) {
  6303. var l = this._curve.length;
  6304. // first and last tangents
  6305. this._tangents[0] = this._getFirstNonNullVector(0);
  6306. if (!this._raw) {
  6307. this._tangents[0].normalize();
  6308. }
  6309. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6310. if (!this._raw) {
  6311. this._tangents[l - 1].normalize();
  6312. }
  6313. // normals and binormals at first point : arbitrary vector with _normalVector()
  6314. var tg0 = this._tangents[0];
  6315. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6316. this._normals[0] = pp0;
  6317. if (!this._raw) {
  6318. this._normals[0].normalize();
  6319. }
  6320. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6321. if (!this._raw) {
  6322. this._binormals[0].normalize();
  6323. }
  6324. this._distances[0] = 0.0;
  6325. // normals and binormals : next points
  6326. var prev; // previous vector (segment)
  6327. var cur; // current vector (segment)
  6328. var curTang; // current tangent
  6329. // previous normal
  6330. var prevBinor; // previous binormal
  6331. for (var i = 1; i < l; i++) {
  6332. // tangents
  6333. prev = this._getLastNonNullVector(i);
  6334. if (i < l - 1) {
  6335. cur = this._getFirstNonNullVector(i);
  6336. this._tangents[i] = prev.add(cur);
  6337. this._tangents[i].normalize();
  6338. }
  6339. this._distances[i] = this._distances[i - 1] + prev.length();
  6340. // normals and binormals
  6341. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6342. curTang = this._tangents[i];
  6343. prevBinor = this._binormals[i - 1];
  6344. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6345. if (!this._raw) {
  6346. this._normals[i].normalize();
  6347. }
  6348. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6349. if (!this._raw) {
  6350. this._binormals[i].normalize();
  6351. }
  6352. }
  6353. };
  6354. // private function getFirstNonNullVector(index)
  6355. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6356. Path3D.prototype._getFirstNonNullVector = function (index) {
  6357. var i = 1;
  6358. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6359. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6360. i++;
  6361. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6362. }
  6363. return nNVector;
  6364. };
  6365. // private function getLastNonNullVector(index)
  6366. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6367. Path3D.prototype._getLastNonNullVector = function (index) {
  6368. var i = 1;
  6369. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6370. while (nLVector.length() === 0 && index > i + 1) {
  6371. i++;
  6372. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6373. }
  6374. return nLVector;
  6375. };
  6376. // private function normalVector(v0, vt, va) :
  6377. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6378. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6379. Path3D.prototype._normalVector = function (v0, vt, va) {
  6380. var normal0;
  6381. var tgl = vt.length();
  6382. if (tgl === 0.0) {
  6383. tgl = 1.0;
  6384. }
  6385. if (va === undefined || va === null) {
  6386. var point;
  6387. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6388. point = new Vector3(0.0, -1.0, 0.0);
  6389. }
  6390. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6391. point = new Vector3(1.0, 0.0, 0.0);
  6392. }
  6393. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6394. point = new Vector3(0.0, 0.0, 1.0);
  6395. }
  6396. else {
  6397. point = Vector3.Zero();
  6398. }
  6399. normal0 = Vector3.Cross(vt, point);
  6400. }
  6401. else {
  6402. normal0 = Vector3.Cross(vt, va);
  6403. Vector3.CrossToRef(normal0, vt, normal0);
  6404. }
  6405. normal0.normalize();
  6406. return normal0;
  6407. };
  6408. return Path3D;
  6409. }());
  6410. BABYLON.Path3D = Path3D;
  6411. var Curve3 = /** @class */ (function () {
  6412. /**
  6413. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6414. * A Curve3 is designed from a series of successive Vector3.
  6415. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6416. */
  6417. function Curve3(points) {
  6418. this._length = 0.0;
  6419. this._points = points;
  6420. this._length = this._computeLength(points);
  6421. }
  6422. /**
  6423. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6424. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6425. * @param v1 (Vector3) the control point
  6426. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6427. * @param nbPoints (integer) the wanted number of points in the curve
  6428. */
  6429. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6430. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6431. var bez = new Array();
  6432. var equation = function (t, val0, val1, val2) {
  6433. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6434. return res;
  6435. };
  6436. for (var i = 0; i <= nbPoints; i++) {
  6437. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  6438. }
  6439. return new Curve3(bez);
  6440. };
  6441. /**
  6442. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6443. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6444. * @param v1 (Vector3) the first control point
  6445. * @param v2 (Vector3) the second control point
  6446. * @param v3 (Vector3) the end point of the Cubic Bezier
  6447. * @param nbPoints (integer) the wanted number of points in the curve
  6448. */
  6449. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6450. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6451. var bez = new Array();
  6452. var equation = function (t, val0, val1, val2, val3) {
  6453. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  6454. return res;
  6455. };
  6456. for (var i = 0; i <= nbPoints; i++) {
  6457. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  6458. }
  6459. return new Curve3(bez);
  6460. };
  6461. /**
  6462. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6463. * @param p1 (Vector3) the origin point of the Hermite Spline
  6464. * @param t1 (Vector3) the tangent vector at the origin point
  6465. * @param p2 (Vector3) the end point of the Hermite Spline
  6466. * @param t2 (Vector3) the tangent vector at the end point
  6467. * @param nbPoints (integer) the wanted number of points in the curve
  6468. */
  6469. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6470. var hermite = new Array();
  6471. var step = 1.0 / nbPoints;
  6472. for (var i = 0; i <= nbPoints; i++) {
  6473. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6474. }
  6475. return new Curve3(hermite);
  6476. };
  6477. /**
  6478. * Returns a Curve3 object along a CatmullRom Spline curve :
  6479. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6480. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6481. */
  6482. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6483. var totalPoints = new Array();
  6484. totalPoints.push(points[0].clone());
  6485. Array.prototype.push.apply(totalPoints, points);
  6486. totalPoints.push(points[points.length - 1].clone());
  6487. var catmullRom = new Array();
  6488. var step = 1.0 / nbPoints;
  6489. var amount = 0.0;
  6490. for (var i = 0; i < totalPoints.length - 3; i++) {
  6491. amount = 0;
  6492. for (var c = 0; c < nbPoints; c++) {
  6493. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6494. amount += step;
  6495. }
  6496. }
  6497. i--;
  6498. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6499. return new Curve3(catmullRom);
  6500. };
  6501. /**
  6502. * Returns the Curve3 stored array of successive Vector3
  6503. */
  6504. Curve3.prototype.getPoints = function () {
  6505. return this._points;
  6506. };
  6507. /**
  6508. * Returns the computed length (float) of the curve.
  6509. */
  6510. Curve3.prototype.length = function () {
  6511. return this._length;
  6512. };
  6513. /**
  6514. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6515. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6516. * curveA and curveB keep unchanged.
  6517. */
  6518. Curve3.prototype.continue = function (curve) {
  6519. var lastPoint = this._points[this._points.length - 1];
  6520. var continuedPoints = this._points.slice();
  6521. var curvePoints = curve.getPoints();
  6522. for (var i = 1; i < curvePoints.length; i++) {
  6523. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6524. }
  6525. var continuedCurve = new Curve3(continuedPoints);
  6526. return continuedCurve;
  6527. };
  6528. Curve3.prototype._computeLength = function (path) {
  6529. var l = 0;
  6530. for (var i = 1; i < path.length; i++) {
  6531. l += (path[i].subtract(path[i - 1])).length();
  6532. }
  6533. return l;
  6534. };
  6535. return Curve3;
  6536. }());
  6537. BABYLON.Curve3 = Curve3;
  6538. // Vertex formats
  6539. var PositionNormalVertex = /** @class */ (function () {
  6540. function PositionNormalVertex(position, normal) {
  6541. if (position === void 0) { position = Vector3.Zero(); }
  6542. if (normal === void 0) { normal = Vector3.Up(); }
  6543. this.position = position;
  6544. this.normal = normal;
  6545. }
  6546. PositionNormalVertex.prototype.clone = function () {
  6547. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6548. };
  6549. return PositionNormalVertex;
  6550. }());
  6551. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6552. var PositionNormalTextureVertex = /** @class */ (function () {
  6553. function PositionNormalTextureVertex(position, normal, uv) {
  6554. if (position === void 0) { position = Vector3.Zero(); }
  6555. if (normal === void 0) { normal = Vector3.Up(); }
  6556. if (uv === void 0) { uv = Vector2.Zero(); }
  6557. this.position = position;
  6558. this.normal = normal;
  6559. this.uv = uv;
  6560. }
  6561. PositionNormalTextureVertex.prototype.clone = function () {
  6562. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6563. };
  6564. return PositionNormalTextureVertex;
  6565. }());
  6566. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6567. // Temporary pre-allocated objects for engine internal use
  6568. // usage in any internal function :
  6569. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6570. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6571. var Tmp = /** @class */ (function () {
  6572. function Tmp() {
  6573. }
  6574. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6575. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6576. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6577. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6578. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6579. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6580. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6581. Matrix.Zero(), Matrix.Zero(),
  6582. Matrix.Zero(), Matrix.Zero(),
  6583. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6584. return Tmp;
  6585. }());
  6586. BABYLON.Tmp = Tmp;
  6587. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6588. var MathTmp = /** @class */ (function () {
  6589. function MathTmp() {
  6590. }
  6591. MathTmp.Vector3 = [Vector3.Zero()];
  6592. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6593. MathTmp.Quaternion = [Quaternion.Zero()];
  6594. return MathTmp;
  6595. }());
  6596. })(BABYLON || (BABYLON = {}));
  6597. //# sourceMappingURL=babylon.math.js.map
  6598. var BABYLON;
  6599. (function (BABYLON) {
  6600. var Scalar = /** @class */ (function () {
  6601. function Scalar() {
  6602. }
  6603. /**
  6604. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6605. */
  6606. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6607. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6608. var num = a - b;
  6609. return -epsilon <= num && num <= epsilon;
  6610. };
  6611. /**
  6612. * Returns a string : the upper case translation of the number i to hexadecimal.
  6613. */
  6614. Scalar.ToHex = function (i) {
  6615. var str = i.toString(16);
  6616. if (i <= 15) {
  6617. return ("0" + str).toUpperCase();
  6618. }
  6619. return str.toUpperCase();
  6620. };
  6621. /**
  6622. * Returns -1 if value is negative and +1 is value is positive.
  6623. * Returns the value itself if it's equal to zero.
  6624. */
  6625. Scalar.Sign = function (value) {
  6626. value = +value; // convert to a number
  6627. if (value === 0 || isNaN(value))
  6628. return value;
  6629. return value > 0 ? 1 : -1;
  6630. };
  6631. /**
  6632. * Returns the value itself if it's between min and max.
  6633. * Returns min if the value is lower than min.
  6634. * Returns max if the value is greater than max.
  6635. */
  6636. Scalar.Clamp = function (value, min, max) {
  6637. if (min === void 0) { min = 0; }
  6638. if (max === void 0) { max = 1; }
  6639. return Math.min(max, Math.max(min, value));
  6640. };
  6641. /**
  6642. * Returns the log2 of value.
  6643. */
  6644. Scalar.Log2 = function (value) {
  6645. return Math.log(value) * Math.LOG2E;
  6646. };
  6647. /**
  6648. * Loops the value, so that it is never larger than length and never smaller than 0.
  6649. *
  6650. * This is similar to the modulo operator but it works with floating point numbers.
  6651. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6652. * With t = 5 and length = 2.5, the result would be 0.0.
  6653. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6654. */
  6655. Scalar.Repeat = function (value, length) {
  6656. return value - Math.floor(value / length) * length;
  6657. };
  6658. /**
  6659. * Normalize the value between 0.0 and 1.0 using min and max values
  6660. */
  6661. Scalar.Normalize = function (value, min, max) {
  6662. return (value - min) / (max - min);
  6663. };
  6664. /**
  6665. * Denormalize the value from 0.0 and 1.0 using min and max values
  6666. */
  6667. Scalar.Denormalize = function (normalized, min, max) {
  6668. return (normalized * (max - min) + min);
  6669. };
  6670. /**
  6671. * Calculates the shortest difference between two given angles given in degrees.
  6672. */
  6673. Scalar.DeltaAngle = function (current, target) {
  6674. var num = Scalar.Repeat(target - current, 360.0);
  6675. if (num > 180.0) {
  6676. num -= 360.0;
  6677. }
  6678. return num;
  6679. };
  6680. /**
  6681. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6682. *
  6683. * The returned value will move back and forth between 0 and length
  6684. */
  6685. Scalar.PingPong = function (tx, length) {
  6686. var t = Scalar.Repeat(tx, length * 2.0);
  6687. return length - Math.abs(t - length);
  6688. };
  6689. /**
  6690. * Interpolates between min and max with smoothing at the limits.
  6691. *
  6692. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6693. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6694. */
  6695. Scalar.SmoothStep = function (from, to, tx) {
  6696. var t = Scalar.Clamp(tx);
  6697. t = -2.0 * t * t * t + 3.0 * t * t;
  6698. return to * t + from * (1.0 - t);
  6699. };
  6700. /**
  6701. * Moves a value current towards target.
  6702. *
  6703. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6704. * Negative values of maxDelta pushes the value away from target.
  6705. */
  6706. Scalar.MoveTowards = function (current, target, maxDelta) {
  6707. var result = 0;
  6708. if (Math.abs(target - current) <= maxDelta) {
  6709. result = target;
  6710. }
  6711. else {
  6712. result = current + Scalar.Sign(target - current) * maxDelta;
  6713. }
  6714. return result;
  6715. };
  6716. /**
  6717. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6718. *
  6719. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6720. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6721. */
  6722. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6723. var num = Scalar.DeltaAngle(current, target);
  6724. var result = 0;
  6725. if (-maxDelta < num && num < maxDelta) {
  6726. result = target;
  6727. }
  6728. else {
  6729. target = current + num;
  6730. result = Scalar.MoveTowards(current, target, maxDelta);
  6731. }
  6732. return result;
  6733. };
  6734. /**
  6735. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6736. */
  6737. Scalar.Lerp = function (start, end, amount) {
  6738. return start + ((end - start) * amount);
  6739. };
  6740. /**
  6741. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6742. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6743. */
  6744. Scalar.LerpAngle = function (start, end, amount) {
  6745. var num = Scalar.Repeat(end - start, 360.0);
  6746. if (num > 180.0) {
  6747. num -= 360.0;
  6748. }
  6749. return start + num * Scalar.Clamp(amount);
  6750. };
  6751. /**
  6752. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6753. */
  6754. Scalar.InverseLerp = function (a, b, value) {
  6755. var result = 0;
  6756. if (a != b) {
  6757. result = Scalar.Clamp((value - a) / (b - a));
  6758. }
  6759. else {
  6760. result = 0.0;
  6761. }
  6762. return result;
  6763. };
  6764. /**
  6765. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6766. */
  6767. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6768. var squared = amount * amount;
  6769. var cubed = amount * squared;
  6770. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6771. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6772. var part3 = (cubed - (2.0 * squared)) + amount;
  6773. var part4 = cubed - squared;
  6774. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6775. };
  6776. /**
  6777. * Returns a random float number between and min and max values
  6778. */
  6779. Scalar.RandomRange = function (min, max) {
  6780. if (min === max)
  6781. return min;
  6782. return ((Math.random() * (max - min)) + min);
  6783. };
  6784. /**
  6785. * This function returns percentage of a number in a given range.
  6786. *
  6787. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6788. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6789. */
  6790. Scalar.RangeToPercent = function (number, min, max) {
  6791. return ((number - min) / (max - min));
  6792. };
  6793. /**
  6794. * This function returns number that corresponds to the percentage in a given range.
  6795. *
  6796. * PercentToRange(0.34,0,100) will return 34.
  6797. */
  6798. Scalar.PercentToRange = function (percent, min, max) {
  6799. return ((max - min) * percent + min);
  6800. };
  6801. /**
  6802. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6803. * @param angle The angle to normalize in radian.
  6804. * @return The converted angle.
  6805. */
  6806. Scalar.NormalizeRadians = function (angle) {
  6807. // More precise but slower version kept for reference.
  6808. // angle = angle % Tools.TwoPi;
  6809. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6810. //if (angle > Math.PI) {
  6811. // angle -= Tools.TwoPi;
  6812. //}
  6813. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6814. return angle;
  6815. };
  6816. /**
  6817. * Two pi constants convenient for computation.
  6818. */
  6819. Scalar.TwoPi = Math.PI * 2;
  6820. return Scalar;
  6821. }());
  6822. BABYLON.Scalar = Scalar;
  6823. })(BABYLON || (BABYLON = {}));
  6824. //# sourceMappingURL=babylon.math.scalar.js.map
  6825. //# sourceMappingURL=babylon.mixins.js.map
  6826. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6827. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6828. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6829. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6830. //# sourceMappingURL=babylon.webgl2.js.map
  6831. var BABYLON;
  6832. (function (BABYLON) {
  6833. var __decoratorInitialStore = {};
  6834. var __mergedStore = {};
  6835. var _copySource = function (creationFunction, source, instanciate) {
  6836. var destination = creationFunction();
  6837. // Tags
  6838. if (BABYLON.Tags) {
  6839. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6840. }
  6841. var classStore = getMergedStore(destination);
  6842. // Properties
  6843. for (var property in classStore) {
  6844. var propertyDescriptor = classStore[property];
  6845. var sourceProperty = source[property];
  6846. var propertyType = propertyDescriptor.type;
  6847. if (sourceProperty !== undefined && sourceProperty !== null) {
  6848. switch (propertyType) {
  6849. case 0: // Value
  6850. case 6:// Mesh reference
  6851. destination[property] = sourceProperty;
  6852. break;
  6853. case 1:// Texture
  6854. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6855. break;
  6856. case 2: // Color3
  6857. case 3: // FresnelParameters
  6858. case 4: // Vector2
  6859. case 5: // Vector3
  6860. case 7: // Color Curves
  6861. case 10:// Quaternion
  6862. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6863. break;
  6864. }
  6865. }
  6866. }
  6867. return destination;
  6868. };
  6869. function getDirectStore(target) {
  6870. var classKey = target.getClassName();
  6871. if (!__decoratorInitialStore[classKey]) {
  6872. __decoratorInitialStore[classKey] = {};
  6873. }
  6874. return __decoratorInitialStore[classKey];
  6875. }
  6876. /**
  6877. * Return the list of properties flagged as serializable
  6878. * @param target: host object
  6879. */
  6880. function getMergedStore(target) {
  6881. var classKey = target.getClassName();
  6882. if (__mergedStore[classKey]) {
  6883. return __mergedStore[classKey];
  6884. }
  6885. __mergedStore[classKey] = {};
  6886. var store = __mergedStore[classKey];
  6887. var currentTarget = target;
  6888. var currentKey = classKey;
  6889. while (currentKey) {
  6890. var initialStore = __decoratorInitialStore[currentKey];
  6891. for (var property in initialStore) {
  6892. store[property] = initialStore[property];
  6893. }
  6894. var parent_1 = void 0;
  6895. var done = false;
  6896. do {
  6897. parent_1 = Object.getPrototypeOf(currentTarget);
  6898. if (!parent_1.getClassName) {
  6899. done = true;
  6900. break;
  6901. }
  6902. if (parent_1.getClassName() !== currentKey) {
  6903. break;
  6904. }
  6905. currentTarget = parent_1;
  6906. } while (parent_1);
  6907. if (done) {
  6908. break;
  6909. }
  6910. currentKey = parent_1.getClassName();
  6911. currentTarget = parent_1;
  6912. }
  6913. return store;
  6914. }
  6915. function generateSerializableMember(type, sourceName) {
  6916. return function (target, propertyKey) {
  6917. var classStore = getDirectStore(target);
  6918. if (!classStore[propertyKey]) {
  6919. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6920. }
  6921. };
  6922. }
  6923. function generateExpandMember(setCallback, targetKey) {
  6924. if (targetKey === void 0) { targetKey = null; }
  6925. return function (target, propertyKey) {
  6926. var key = targetKey || ("_" + propertyKey);
  6927. Object.defineProperty(target, propertyKey, {
  6928. get: function () {
  6929. return this[key];
  6930. },
  6931. set: function (value) {
  6932. if (this[key] === value) {
  6933. return;
  6934. }
  6935. this[key] = value;
  6936. target[setCallback].apply(this);
  6937. },
  6938. enumerable: true,
  6939. configurable: true
  6940. });
  6941. };
  6942. }
  6943. function expandToProperty(callback, targetKey) {
  6944. if (targetKey === void 0) { targetKey = null; }
  6945. return generateExpandMember(callback, targetKey);
  6946. }
  6947. BABYLON.expandToProperty = expandToProperty;
  6948. function serialize(sourceName) {
  6949. return generateSerializableMember(0, sourceName); // value member
  6950. }
  6951. BABYLON.serialize = serialize;
  6952. function serializeAsTexture(sourceName) {
  6953. return generateSerializableMember(1, sourceName); // texture member
  6954. }
  6955. BABYLON.serializeAsTexture = serializeAsTexture;
  6956. function serializeAsColor3(sourceName) {
  6957. return generateSerializableMember(2, sourceName); // color3 member
  6958. }
  6959. BABYLON.serializeAsColor3 = serializeAsColor3;
  6960. function serializeAsFresnelParameters(sourceName) {
  6961. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6962. }
  6963. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6964. function serializeAsVector2(sourceName) {
  6965. return generateSerializableMember(4, sourceName); // vector2 member
  6966. }
  6967. BABYLON.serializeAsVector2 = serializeAsVector2;
  6968. function serializeAsVector3(sourceName) {
  6969. return generateSerializableMember(5, sourceName); // vector3 member
  6970. }
  6971. BABYLON.serializeAsVector3 = serializeAsVector3;
  6972. function serializeAsMeshReference(sourceName) {
  6973. return generateSerializableMember(6, sourceName); // mesh reference member
  6974. }
  6975. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6976. function serializeAsColorCurves(sourceName) {
  6977. return generateSerializableMember(7, sourceName); // color curves
  6978. }
  6979. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6980. function serializeAsColor4(sourceName) {
  6981. return generateSerializableMember(8, sourceName); // color 4
  6982. }
  6983. BABYLON.serializeAsColor4 = serializeAsColor4;
  6984. function serializeAsImageProcessingConfiguration(sourceName) {
  6985. return generateSerializableMember(9, sourceName); // image processing
  6986. }
  6987. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  6988. function serializeAsQuaternion(sourceName) {
  6989. return generateSerializableMember(10, sourceName); // quaternion member
  6990. }
  6991. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  6992. var SerializationHelper = /** @class */ (function () {
  6993. function SerializationHelper() {
  6994. }
  6995. SerializationHelper.Serialize = function (entity, serializationObject) {
  6996. if (!serializationObject) {
  6997. serializationObject = {};
  6998. }
  6999. // Tags
  7000. if (BABYLON.Tags) {
  7001. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7002. }
  7003. var serializedProperties = getMergedStore(entity);
  7004. // Properties
  7005. for (var property in serializedProperties) {
  7006. var propertyDescriptor = serializedProperties[property];
  7007. var targetPropertyName = propertyDescriptor.sourceName || property;
  7008. var propertyType = propertyDescriptor.type;
  7009. var sourceProperty = entity[property];
  7010. if (sourceProperty !== undefined && sourceProperty !== null) {
  7011. switch (propertyType) {
  7012. case 0:// Value
  7013. serializationObject[targetPropertyName] = sourceProperty;
  7014. break;
  7015. case 1:// Texture
  7016. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7017. break;
  7018. case 2:// Color3
  7019. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7020. break;
  7021. case 3:// FresnelParameters
  7022. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7023. break;
  7024. case 4:// Vector2
  7025. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7026. break;
  7027. case 5:// Vector3
  7028. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7029. break;
  7030. case 6:// Mesh reference
  7031. serializationObject[targetPropertyName] = sourceProperty.id;
  7032. break;
  7033. case 7:// Color Curves
  7034. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7035. break;
  7036. case 8:// Color 4
  7037. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7038. break;
  7039. case 9:// Image Processing
  7040. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7041. break;
  7042. }
  7043. }
  7044. }
  7045. return serializationObject;
  7046. };
  7047. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7048. if (rootUrl === void 0) { rootUrl = null; }
  7049. var destination = creationFunction();
  7050. if (!rootUrl) {
  7051. rootUrl = "";
  7052. }
  7053. // Tags
  7054. if (BABYLON.Tags) {
  7055. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7056. }
  7057. var classStore = getMergedStore(destination);
  7058. // Properties
  7059. for (var property in classStore) {
  7060. var propertyDescriptor = classStore[property];
  7061. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7062. var propertyType = propertyDescriptor.type;
  7063. if (sourceProperty !== undefined && sourceProperty !== null) {
  7064. var dest = destination;
  7065. switch (propertyType) {
  7066. case 0:// Value
  7067. dest[property] = sourceProperty;
  7068. break;
  7069. case 1:// Texture
  7070. if (scene) {
  7071. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7072. }
  7073. break;
  7074. case 2:// Color3
  7075. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7076. break;
  7077. case 3:// FresnelParameters
  7078. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7079. break;
  7080. case 4:// Vector2
  7081. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7082. break;
  7083. case 5:// Vector3
  7084. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7085. break;
  7086. case 6:// Mesh reference
  7087. if (scene) {
  7088. dest[property] = scene.getLastMeshByID(sourceProperty);
  7089. }
  7090. break;
  7091. case 7:// Color Curves
  7092. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7093. break;
  7094. case 8:// Color 4
  7095. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7096. break;
  7097. case 9:// Image Processing
  7098. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7099. break;
  7100. }
  7101. }
  7102. }
  7103. return destination;
  7104. };
  7105. SerializationHelper.Clone = function (creationFunction, source) {
  7106. return _copySource(creationFunction, source, false);
  7107. };
  7108. SerializationHelper.Instanciate = function (creationFunction, source) {
  7109. return _copySource(creationFunction, source, true);
  7110. };
  7111. return SerializationHelper;
  7112. }());
  7113. BABYLON.SerializationHelper = SerializationHelper;
  7114. })(BABYLON || (BABYLON = {}));
  7115. //# sourceMappingURL=babylon.decorators.js.map
  7116. var BABYLON;
  7117. (function (BABYLON) {
  7118. /**
  7119. * A class serves as a medium between the observable and its observers
  7120. */
  7121. var EventState = /** @class */ (function () {
  7122. /**
  7123. * Create a new EventState
  7124. * @param mask defines the mask associated with this state
  7125. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7126. * @param target defines the original target of the state
  7127. * @param currentTarget defines the current target of the state
  7128. */
  7129. function EventState(mask, skipNextObservers, target, currentTarget) {
  7130. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7131. this.initalize(mask, skipNextObservers, target, currentTarget);
  7132. }
  7133. /**
  7134. * Initialize the current event state
  7135. * @param mask defines the mask associated with this state
  7136. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7137. * @param target defines the original target of the state
  7138. * @param currentTarget defines the current target of the state
  7139. * @returns the current event state
  7140. */
  7141. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7142. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7143. this.mask = mask;
  7144. this.skipNextObservers = skipNextObservers;
  7145. this.target = target;
  7146. this.currentTarget = currentTarget;
  7147. return this;
  7148. };
  7149. return EventState;
  7150. }());
  7151. BABYLON.EventState = EventState;
  7152. /**
  7153. * Represent an Observer registered to a given Observable object.
  7154. */
  7155. var Observer = /** @class */ (function () {
  7156. /**
  7157. * Creates a new observer
  7158. * @param callback defines the callback to call when the observer is notified
  7159. * @param mask defines the mask of the observer (used to filter notifications)
  7160. * @param scope defines the current scope used to restore the JS context
  7161. */
  7162. function Observer(
  7163. /**
  7164. * Defines the callback to call when the observer is notified
  7165. */
  7166. callback,
  7167. /**
  7168. * Defines the mask of the observer (used to filter notifications)
  7169. */
  7170. mask,
  7171. /**
  7172. * Defines the current scope used to restore the JS context
  7173. */
  7174. scope) {
  7175. if (scope === void 0) { scope = null; }
  7176. this.callback = callback;
  7177. this.mask = mask;
  7178. this.scope = scope;
  7179. /** @ignore */
  7180. this._willBeUnregistered = false;
  7181. /**
  7182. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7183. */
  7184. this.unregisterOnNextCall = false;
  7185. }
  7186. return Observer;
  7187. }());
  7188. BABYLON.Observer = Observer;
  7189. /**
  7190. * Represent a list of observers registered to multiple Observables object.
  7191. */
  7192. var MultiObserver = /** @class */ (function () {
  7193. function MultiObserver() {
  7194. }
  7195. /**
  7196. * Release associated resources
  7197. */
  7198. MultiObserver.prototype.dispose = function () {
  7199. if (this._observers && this._observables) {
  7200. for (var index = 0; index < this._observers.length; index++) {
  7201. this._observables[index].remove(this._observers[index]);
  7202. }
  7203. }
  7204. this._observers = null;
  7205. this._observables = null;
  7206. };
  7207. /**
  7208. * Raise a callback when one of the observable will notify
  7209. * @param observables defines a list of observables to watch
  7210. * @param callback defines the callback to call on notification
  7211. * @param mask defines the mask used to filter notifications
  7212. * @param scope defines the current scope used to restore the JS context
  7213. * @returns the new MultiObserver
  7214. */
  7215. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7216. if (mask === void 0) { mask = -1; }
  7217. if (scope === void 0) { scope = null; }
  7218. var result = new MultiObserver();
  7219. result._observers = new Array();
  7220. result._observables = observables;
  7221. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7222. var observable = observables_1[_i];
  7223. var observer = observable.add(callback, mask, false, scope);
  7224. if (observer) {
  7225. result._observers.push(observer);
  7226. }
  7227. }
  7228. return result;
  7229. };
  7230. return MultiObserver;
  7231. }());
  7232. BABYLON.MultiObserver = MultiObserver;
  7233. /**
  7234. * The Observable class is a simple implementation of the Observable pattern.
  7235. * 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.
  7236. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7237. * 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).
  7238. * 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.
  7239. */
  7240. var Observable = /** @class */ (function () {
  7241. /**
  7242. * Creates a new observable
  7243. * @param onObserverAdded defines a callback to call when a new observer is added
  7244. */
  7245. function Observable(onObserverAdded) {
  7246. this._observers = new Array();
  7247. this._eventState = new EventState(0);
  7248. if (onObserverAdded) {
  7249. this._onObserverAdded = onObserverAdded;
  7250. }
  7251. }
  7252. /**
  7253. * Create a new Observer with the specified callback
  7254. * @param callback the callback that will be executed for that Observer
  7255. * @param mask the mask used to filter observers
  7256. * @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.
  7257. * @param scope optional scope for the callback to be called from
  7258. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7259. * @returns the new observer created for the callback
  7260. */
  7261. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7262. if (mask === void 0) { mask = -1; }
  7263. if (insertFirst === void 0) { insertFirst = false; }
  7264. if (scope === void 0) { scope = null; }
  7265. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7266. if (!callback) {
  7267. return null;
  7268. }
  7269. var observer = new Observer(callback, mask, scope);
  7270. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7271. if (insertFirst) {
  7272. this._observers.unshift(observer);
  7273. }
  7274. else {
  7275. this._observers.push(observer);
  7276. }
  7277. if (this._onObserverAdded) {
  7278. this._onObserverAdded(observer);
  7279. }
  7280. return observer;
  7281. };
  7282. /**
  7283. * Remove an Observer from the Observable object
  7284. * @param observer the instance of the Observer to remove
  7285. * @returns false if it doesn't belong to this Observable
  7286. */
  7287. Observable.prototype.remove = function (observer) {
  7288. if (!observer) {
  7289. return false;
  7290. }
  7291. var index = this._observers.indexOf(observer);
  7292. if (index !== -1) {
  7293. this._observers.splice(index, 1);
  7294. return true;
  7295. }
  7296. return false;
  7297. };
  7298. /**
  7299. * Remove a callback from the Observable object
  7300. * @param callback the callback to remove
  7301. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7302. * @returns false if it doesn't belong to this Observable
  7303. */
  7304. Observable.prototype.removeCallback = function (callback, scope) {
  7305. for (var index = 0; index < this._observers.length; index++) {
  7306. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7307. this._observers.splice(index, 1);
  7308. return true;
  7309. }
  7310. }
  7311. return false;
  7312. };
  7313. Observable.prototype._deferUnregister = function (observer) {
  7314. var _this = this;
  7315. observer.unregisterOnNextCall = false;
  7316. observer._willBeUnregistered = true;
  7317. BABYLON.Tools.SetImmediate(function () {
  7318. _this.remove(observer);
  7319. });
  7320. };
  7321. /**
  7322. * Notify all Observers by calling their respective callback with the given data
  7323. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7324. * @param eventData defines the data to send to all observers
  7325. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7326. * @param target defines the original target of the state
  7327. * @param currentTarget defines the current target of the state
  7328. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7329. */
  7330. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7331. if (mask === void 0) { mask = -1; }
  7332. if (!this._observers.length) {
  7333. return true;
  7334. }
  7335. var state = this._eventState;
  7336. state.mask = mask;
  7337. state.target = target;
  7338. state.currentTarget = currentTarget;
  7339. state.skipNextObservers = false;
  7340. state.lastReturnValue = eventData;
  7341. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7342. var obs = _a[_i];
  7343. if (obs._willBeUnregistered) {
  7344. continue;
  7345. }
  7346. if (obs.mask & mask) {
  7347. if (obs.scope) {
  7348. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7349. }
  7350. else {
  7351. state.lastReturnValue = obs.callback(eventData, state);
  7352. }
  7353. if (obs.unregisterOnNextCall) {
  7354. this._deferUnregister(obs);
  7355. }
  7356. }
  7357. if (state.skipNextObservers) {
  7358. return false;
  7359. }
  7360. }
  7361. return true;
  7362. };
  7363. /**
  7364. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7365. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7366. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7367. * and it is crucial that all callbacks will be executed.
  7368. * The order of the callbacks is kept, callbacks are not executed parallel.
  7369. *
  7370. * @param eventData The data to be sent to each callback
  7371. * @param mask is used to filter observers defaults to -1
  7372. * @param target defines the callback target (see EventState)
  7373. * @param currentTarget defines he current object in the bubbling phase
  7374. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7375. */
  7376. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7377. var _this = this;
  7378. if (mask === void 0) { mask = -1; }
  7379. // create an empty promise
  7380. var p = Promise.resolve(eventData);
  7381. // no observers? return this promise.
  7382. if (!this._observers.length) {
  7383. return p;
  7384. }
  7385. var state = this._eventState;
  7386. state.mask = mask;
  7387. state.target = target;
  7388. state.currentTarget = currentTarget;
  7389. state.skipNextObservers = false;
  7390. // execute one callback after another (not using Promise.all, the order is important)
  7391. this._observers.forEach(function (obs) {
  7392. if (state.skipNextObservers) {
  7393. return;
  7394. }
  7395. if (obs._willBeUnregistered) {
  7396. return;
  7397. }
  7398. if (obs.mask & mask) {
  7399. if (obs.scope) {
  7400. p = p.then(function (lastReturnedValue) {
  7401. state.lastReturnValue = lastReturnedValue;
  7402. return obs.callback.apply(obs.scope, [eventData, state]);
  7403. });
  7404. }
  7405. else {
  7406. p = p.then(function (lastReturnedValue) {
  7407. state.lastReturnValue = lastReturnedValue;
  7408. return obs.callback(eventData, state);
  7409. });
  7410. }
  7411. if (obs.unregisterOnNextCall) {
  7412. _this._deferUnregister(obs);
  7413. }
  7414. }
  7415. });
  7416. // return the eventData
  7417. return p.then(function () { return eventData; });
  7418. };
  7419. /**
  7420. * Notify a specific observer
  7421. * @param observer defines the observer to notify
  7422. * @param eventData defines the data to be sent to each callback
  7423. * @param mask is used to filter observers defaults to -1
  7424. */
  7425. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7426. if (mask === void 0) { mask = -1; }
  7427. var state = this._eventState;
  7428. state.mask = mask;
  7429. state.skipNextObservers = false;
  7430. observer.callback(eventData, state);
  7431. };
  7432. /**
  7433. * Gets a boolean indicating if the observable has at least one observer
  7434. * @returns true is the Observable has at least one Observer registered
  7435. */
  7436. Observable.prototype.hasObservers = function () {
  7437. return this._observers.length > 0;
  7438. };
  7439. /**
  7440. * Clear the list of observers
  7441. */
  7442. Observable.prototype.clear = function () {
  7443. this._observers = new Array();
  7444. this._onObserverAdded = null;
  7445. };
  7446. /**
  7447. * Clone the current observable
  7448. * @returns a new observable
  7449. */
  7450. Observable.prototype.clone = function () {
  7451. var result = new Observable();
  7452. result._observers = this._observers.slice(0);
  7453. return result;
  7454. };
  7455. /**
  7456. * Does this observable handles observer registered with a given mask
  7457. * @param mask defines the mask to be tested
  7458. * @return whether or not one observer registered with the given mask is handeled
  7459. **/
  7460. Observable.prototype.hasSpecificMask = function (mask) {
  7461. if (mask === void 0) { mask = -1; }
  7462. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7463. var obs = _a[_i];
  7464. if (obs.mask & mask || obs.mask === mask) {
  7465. return true;
  7466. }
  7467. }
  7468. return false;
  7469. };
  7470. return Observable;
  7471. }());
  7472. BABYLON.Observable = Observable;
  7473. })(BABYLON || (BABYLON = {}));
  7474. //# sourceMappingURL=babylon.observable.js.map
  7475. var BABYLON;
  7476. (function (BABYLON) {
  7477. var SmartArray = /** @class */ (function () {
  7478. function SmartArray(capacity) {
  7479. this.length = 0;
  7480. this.data = new Array(capacity);
  7481. this._id = SmartArray._GlobalId++;
  7482. }
  7483. SmartArray.prototype.push = function (value) {
  7484. this.data[this.length++] = value;
  7485. if (this.length > this.data.length) {
  7486. this.data.length *= 2;
  7487. }
  7488. };
  7489. SmartArray.prototype.forEach = function (func) {
  7490. for (var index = 0; index < this.length; index++) {
  7491. func(this.data[index]);
  7492. }
  7493. };
  7494. SmartArray.prototype.sort = function (compareFn) {
  7495. this.data.sort(compareFn);
  7496. };
  7497. SmartArray.prototype.reset = function () {
  7498. this.length = 0;
  7499. };
  7500. SmartArray.prototype.dispose = function () {
  7501. this.reset();
  7502. if (this.data) {
  7503. this.data.length = 0;
  7504. this.data = [];
  7505. }
  7506. };
  7507. SmartArray.prototype.concat = function (array) {
  7508. if (array.length === 0) {
  7509. return;
  7510. }
  7511. if (this.length + array.length > this.data.length) {
  7512. this.data.length = (this.length + array.length) * 2;
  7513. }
  7514. for (var index = 0; index < array.length; index++) {
  7515. this.data[this.length++] = (array.data || array)[index];
  7516. }
  7517. };
  7518. SmartArray.prototype.indexOf = function (value) {
  7519. var position = this.data.indexOf(value);
  7520. if (position >= this.length) {
  7521. return -1;
  7522. }
  7523. return position;
  7524. };
  7525. SmartArray.prototype.contains = function (value) {
  7526. return this.data.indexOf(value) !== -1;
  7527. };
  7528. // Statics
  7529. SmartArray._GlobalId = 0;
  7530. return SmartArray;
  7531. }());
  7532. BABYLON.SmartArray = SmartArray;
  7533. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7534. __extends(SmartArrayNoDuplicate, _super);
  7535. function SmartArrayNoDuplicate() {
  7536. var _this = _super !== null && _super.apply(this, arguments) || this;
  7537. _this._duplicateId = 0;
  7538. return _this;
  7539. }
  7540. SmartArrayNoDuplicate.prototype.push = function (value) {
  7541. _super.prototype.push.call(this, value);
  7542. if (!value.__smartArrayFlags) {
  7543. value.__smartArrayFlags = {};
  7544. }
  7545. value.__smartArrayFlags[this._id] = this._duplicateId;
  7546. };
  7547. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7548. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7549. return false;
  7550. }
  7551. this.push(value);
  7552. return true;
  7553. };
  7554. SmartArrayNoDuplicate.prototype.reset = function () {
  7555. _super.prototype.reset.call(this);
  7556. this._duplicateId++;
  7557. };
  7558. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7559. if (array.length === 0) {
  7560. return;
  7561. }
  7562. if (this.length + array.length > this.data.length) {
  7563. this.data.length = (this.length + array.length) * 2;
  7564. }
  7565. for (var index = 0; index < array.length; index++) {
  7566. var item = (array.data || array)[index];
  7567. this.pushNoDuplicate(item);
  7568. }
  7569. };
  7570. return SmartArrayNoDuplicate;
  7571. }(SmartArray));
  7572. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7573. })(BABYLON || (BABYLON = {}));
  7574. //# sourceMappingURL=babylon.smartArray.js.map
  7575. var BABYLON;
  7576. (function (BABYLON) {
  7577. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7578. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7579. var LoadFileError = /** @class */ (function (_super) {
  7580. __extends(LoadFileError, _super);
  7581. function LoadFileError(message, request) {
  7582. var _this = _super.call(this, message) || this;
  7583. _this.request = request;
  7584. _this.name = "LoadFileError";
  7585. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7586. return _this;
  7587. }
  7588. // Polyfill for Object.setPrototypeOf if necessary.
  7589. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7590. return LoadFileError;
  7591. }(Error));
  7592. BABYLON.LoadFileError = LoadFileError;
  7593. var RetryStrategy = /** @class */ (function () {
  7594. function RetryStrategy() {
  7595. }
  7596. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7597. if (maxRetries === void 0) { maxRetries = 3; }
  7598. if (baseInterval === void 0) { baseInterval = 500; }
  7599. return function (url, request, retryIndex) {
  7600. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7601. return -1;
  7602. }
  7603. return Math.pow(2, retryIndex) * baseInterval;
  7604. };
  7605. };
  7606. return RetryStrategy;
  7607. }());
  7608. BABYLON.RetryStrategy = RetryStrategy;
  7609. // Screenshots
  7610. var screenshotCanvas;
  7611. var cloneValue = function (source, destinationObject) {
  7612. if (!source)
  7613. return null;
  7614. if (source instanceof BABYLON.Mesh) {
  7615. return null;
  7616. }
  7617. if (source instanceof BABYLON.SubMesh) {
  7618. return source.clone(destinationObject);
  7619. }
  7620. else if (source.clone) {
  7621. return source.clone();
  7622. }
  7623. return null;
  7624. };
  7625. var Tools = /** @class */ (function () {
  7626. function Tools() {
  7627. }
  7628. /**
  7629. * Interpolates between a and b via alpha
  7630. * @param a The lower value (returned when alpha = 0)
  7631. * @param b The upper value (returned when alpha = 1)
  7632. * @param alpha The interpolation-factor
  7633. * @return The mixed value
  7634. */
  7635. Tools.Mix = function (a, b, alpha) {
  7636. return a * (1 - alpha) + b * alpha;
  7637. };
  7638. Tools.Instantiate = function (className) {
  7639. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7640. return Tools.RegisteredExternalClasses[className];
  7641. }
  7642. var arr = className.split(".");
  7643. var fn = (window || this);
  7644. for (var i = 0, len = arr.length; i < len; i++) {
  7645. fn = fn[arr[i]];
  7646. }
  7647. if (typeof fn !== "function") {
  7648. return null;
  7649. }
  7650. return fn;
  7651. };
  7652. /**
  7653. * Provides a slice function that will work even on IE
  7654. * @param data defines the array to slice
  7655. * @returns the new sliced array
  7656. */
  7657. Tools.Slice = function (data) {
  7658. if (data.slice) {
  7659. return data.slice();
  7660. }
  7661. return Array.prototype.slice.call(data);
  7662. };
  7663. Tools.SetImmediate = function (action) {
  7664. if (window.setImmediate) {
  7665. window.setImmediate(action);
  7666. }
  7667. else {
  7668. setTimeout(action, 1);
  7669. }
  7670. };
  7671. Tools.IsExponentOfTwo = function (value) {
  7672. var count = 1;
  7673. do {
  7674. count *= 2;
  7675. } while (count < value);
  7676. return count === value;
  7677. };
  7678. /**
  7679. * Find the next highest power of two.
  7680. * @param x Number to start search from.
  7681. * @return Next highest power of two.
  7682. */
  7683. Tools.CeilingPOT = function (x) {
  7684. x--;
  7685. x |= x >> 1;
  7686. x |= x >> 2;
  7687. x |= x >> 4;
  7688. x |= x >> 8;
  7689. x |= x >> 16;
  7690. x++;
  7691. return x;
  7692. };
  7693. /**
  7694. * Find the next lowest power of two.
  7695. * @param x Number to start search from.
  7696. * @return Next lowest power of two.
  7697. */
  7698. Tools.FloorPOT = function (x) {
  7699. x = x | (x >> 1);
  7700. x = x | (x >> 2);
  7701. x = x | (x >> 4);
  7702. x = x | (x >> 8);
  7703. x = x | (x >> 16);
  7704. return x - (x >> 1);
  7705. };
  7706. /**
  7707. * Find the nearest power of two.
  7708. * @param x Number to start search from.
  7709. * @return Next nearest power of two.
  7710. */
  7711. Tools.NearestPOT = function (x) {
  7712. var c = Tools.CeilingPOT(x);
  7713. var f = Tools.FloorPOT(x);
  7714. return (c - x) > (x - f) ? f : c;
  7715. };
  7716. Tools.GetExponentOfTwo = function (value, max, mode) {
  7717. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7718. var pot;
  7719. switch (mode) {
  7720. case BABYLON.Engine.SCALEMODE_FLOOR:
  7721. pot = Tools.FloorPOT(value);
  7722. break;
  7723. case BABYLON.Engine.SCALEMODE_NEAREST:
  7724. pot = Tools.NearestPOT(value);
  7725. break;
  7726. case BABYLON.Engine.SCALEMODE_CEILING:
  7727. default:
  7728. pot = Tools.CeilingPOT(value);
  7729. break;
  7730. }
  7731. return Math.min(pot, max);
  7732. };
  7733. Tools.GetFilename = function (path) {
  7734. var index = path.lastIndexOf("/");
  7735. if (index < 0)
  7736. return path;
  7737. return path.substring(index + 1);
  7738. };
  7739. /**
  7740. * Extracts the "folder" part of a path (everything before the filename).
  7741. * @param uri The URI to extract the info from
  7742. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7743. * @returns The "folder" part of the path
  7744. */
  7745. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7746. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7747. var index = uri.lastIndexOf("/");
  7748. if (index < 0) {
  7749. if (returnUnchangedIfNoSlash) {
  7750. return uri;
  7751. }
  7752. return "";
  7753. }
  7754. return uri.substring(0, index + 1);
  7755. };
  7756. Tools.GetDOMTextContent = function (element) {
  7757. var result = "";
  7758. var child = element.firstChild;
  7759. while (child) {
  7760. if (child.nodeType === 3) {
  7761. result += child.textContent;
  7762. }
  7763. child = child.nextSibling;
  7764. }
  7765. return result;
  7766. };
  7767. Tools.ToDegrees = function (angle) {
  7768. return angle * 180 / Math.PI;
  7769. };
  7770. Tools.ToRadians = function (angle) {
  7771. return angle * Math.PI / 180;
  7772. };
  7773. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7774. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7775. var output = "";
  7776. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7777. var i = 0;
  7778. var bytes = new Uint8Array(buffer);
  7779. while (i < bytes.length) {
  7780. chr1 = bytes[i++];
  7781. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7782. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7783. enc1 = chr1 >> 2;
  7784. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7785. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7786. enc4 = chr3 & 63;
  7787. if (isNaN(chr2)) {
  7788. enc3 = enc4 = 64;
  7789. }
  7790. else if (isNaN(chr3)) {
  7791. enc4 = 64;
  7792. }
  7793. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7794. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7795. }
  7796. return "data:image/png;base64," + output;
  7797. };
  7798. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7799. if (bias === void 0) { bias = null; }
  7800. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7801. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7802. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7803. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7804. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7805. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7806. }
  7807. if (bias) {
  7808. minimum.x -= minimum.x * bias.x + bias.y;
  7809. minimum.y -= minimum.y * bias.x + bias.y;
  7810. minimum.z -= minimum.z * bias.x + bias.y;
  7811. maximum.x += maximum.x * bias.x + bias.y;
  7812. maximum.y += maximum.y * bias.x + bias.y;
  7813. maximum.z += maximum.z * bias.x + bias.y;
  7814. }
  7815. return {
  7816. minimum: minimum,
  7817. maximum: maximum
  7818. };
  7819. };
  7820. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7821. if (bias === void 0) { bias = null; }
  7822. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7823. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7824. if (!stride) {
  7825. stride = 3;
  7826. }
  7827. for (var index = start; index < start + count; index++) {
  7828. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7829. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7830. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7831. }
  7832. if (bias) {
  7833. minimum.x -= minimum.x * bias.x + bias.y;
  7834. minimum.y -= minimum.y * bias.x + bias.y;
  7835. minimum.z -= minimum.z * bias.x + bias.y;
  7836. maximum.x += maximum.x * bias.x + bias.y;
  7837. maximum.y += maximum.y * bias.x + bias.y;
  7838. maximum.z += maximum.z * bias.x + bias.y;
  7839. }
  7840. return {
  7841. minimum: minimum,
  7842. maximum: maximum
  7843. };
  7844. };
  7845. Tools.Vector2ArrayFeeder = function (array) {
  7846. return function (index) {
  7847. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7848. var length = isFloatArray ? array.length / 2 : array.length;
  7849. if (index >= length) {
  7850. return null;
  7851. }
  7852. if (isFloatArray) {
  7853. var fa = array;
  7854. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7855. }
  7856. var a = array;
  7857. return a[index];
  7858. };
  7859. };
  7860. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7861. if (bias === void 0) { bias = null; }
  7862. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7863. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7864. var i = 0;
  7865. var cur = feeder(i++);
  7866. while (cur) {
  7867. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7868. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7869. cur = feeder(i++);
  7870. }
  7871. if (bias) {
  7872. minimum.x -= minimum.x * bias.x + bias.y;
  7873. minimum.y -= minimum.y * bias.x + bias.y;
  7874. maximum.x += maximum.x * bias.x + bias.y;
  7875. maximum.y += maximum.y * bias.x + bias.y;
  7876. }
  7877. return {
  7878. minimum: minimum,
  7879. maximum: maximum
  7880. };
  7881. };
  7882. Tools.MakeArray = function (obj, allowsNullUndefined) {
  7883. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  7884. return null;
  7885. return Array.isArray(obj) ? obj : [obj];
  7886. };
  7887. // Misc.
  7888. Tools.GetPointerPrefix = function () {
  7889. var eventPrefix = "pointer";
  7890. // Check if pointer events are supported
  7891. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  7892. eventPrefix = "mouse";
  7893. }
  7894. return eventPrefix;
  7895. };
  7896. /**
  7897. * @param func - the function to be called
  7898. * @param requester - the object that will request the next frame. Falls back to window.
  7899. */
  7900. Tools.QueueNewFrame = function (func, requester) {
  7901. if (!Tools.IsWindowObjectExist()) {
  7902. return setTimeout(func, 16);
  7903. }
  7904. if (!requester) {
  7905. requester = window;
  7906. }
  7907. if (requester.requestAnimationFrame) {
  7908. return requester.requestAnimationFrame(func);
  7909. }
  7910. else if (requester.msRequestAnimationFrame) {
  7911. return requester.msRequestAnimationFrame(func);
  7912. }
  7913. else if (requester.webkitRequestAnimationFrame) {
  7914. return requester.webkitRequestAnimationFrame(func);
  7915. }
  7916. else if (requester.mozRequestAnimationFrame) {
  7917. return requester.mozRequestAnimationFrame(func);
  7918. }
  7919. else if (requester.oRequestAnimationFrame) {
  7920. return requester.oRequestAnimationFrame(func);
  7921. }
  7922. else {
  7923. return window.setTimeout(func, 16);
  7924. }
  7925. };
  7926. Tools.RequestFullscreen = function (element) {
  7927. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  7928. if (!requestFunction)
  7929. return;
  7930. requestFunction.call(element);
  7931. };
  7932. Tools.ExitFullscreen = function () {
  7933. if (document.exitFullscreen) {
  7934. document.exitFullscreen();
  7935. }
  7936. else if (document.mozCancelFullScreen) {
  7937. document.mozCancelFullScreen();
  7938. }
  7939. else if (document.webkitCancelFullScreen) {
  7940. document.webkitCancelFullScreen();
  7941. }
  7942. else if (document.msCancelFullScreen) {
  7943. document.msCancelFullScreen();
  7944. }
  7945. };
  7946. Tools.SetCorsBehavior = function (url, element) {
  7947. if (url && url.indexOf("data:") === 0) {
  7948. return;
  7949. }
  7950. if (Tools.CorsBehavior) {
  7951. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  7952. element.crossOrigin = Tools.CorsBehavior;
  7953. }
  7954. else {
  7955. var result = Tools.CorsBehavior(url);
  7956. if (result) {
  7957. element.crossOrigin = result;
  7958. }
  7959. }
  7960. }
  7961. };
  7962. // External files
  7963. Tools.CleanUrl = function (url) {
  7964. url = url.replace(/#/mg, "%23");
  7965. return url;
  7966. };
  7967. Tools.LoadImage = function (url, onLoad, onError, database) {
  7968. if (url instanceof ArrayBuffer) {
  7969. url = Tools.EncodeArrayBufferTobase64(url);
  7970. }
  7971. url = Tools.CleanUrl(url);
  7972. url = Tools.PreprocessUrl(url);
  7973. var img = new Image();
  7974. Tools.SetCorsBehavior(url, img);
  7975. img.onload = function () {
  7976. onLoad(img);
  7977. };
  7978. img.onerror = function (err) {
  7979. Tools.Error("Error while trying to load image: " + url);
  7980. if (onError) {
  7981. onError("Error while trying to load image: " + url, err);
  7982. }
  7983. };
  7984. var noIndexedDB = function () {
  7985. img.src = url;
  7986. };
  7987. var loadFromIndexedDB = function () {
  7988. if (database) {
  7989. database.loadImageFromDB(url, img);
  7990. }
  7991. };
  7992. //ANY database to do!
  7993. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  7994. database.openAsync(loadFromIndexedDB, noIndexedDB);
  7995. }
  7996. else {
  7997. if (url.indexOf("file:") !== -1) {
  7998. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  7999. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8000. try {
  8001. var blobURL;
  8002. try {
  8003. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8004. }
  8005. catch (ex) {
  8006. // Chrome doesn't support oneTimeOnly parameter
  8007. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8008. }
  8009. img.src = blobURL;
  8010. }
  8011. catch (e) {
  8012. img.src = "";
  8013. }
  8014. return img;
  8015. }
  8016. }
  8017. noIndexedDB();
  8018. }
  8019. return img;
  8020. };
  8021. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8022. url = Tools.CleanUrl(url);
  8023. url = Tools.PreprocessUrl(url);
  8024. // If file and file input are set
  8025. if (url.indexOf("file:") !== -1) {
  8026. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8027. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8028. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8029. }
  8030. }
  8031. var loadUrl = Tools.BaseUrl + url;
  8032. var aborted = false;
  8033. var fileRequest = {
  8034. onCompleteObservable: new BABYLON.Observable(),
  8035. abort: function () { return aborted = true; },
  8036. };
  8037. var requestFile = function () {
  8038. var request = new XMLHttpRequest();
  8039. var retryHandle = null;
  8040. fileRequest.abort = function () {
  8041. aborted = true;
  8042. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8043. request.abort();
  8044. }
  8045. if (retryHandle !== null) {
  8046. clearTimeout(retryHandle);
  8047. retryHandle = null;
  8048. }
  8049. };
  8050. var retryLoop = function (retryIndex) {
  8051. request.open('GET', loadUrl, true);
  8052. if (useArrayBuffer) {
  8053. request.responseType = "arraybuffer";
  8054. }
  8055. if (onProgress) {
  8056. request.addEventListener("progress", onProgress);
  8057. }
  8058. var onLoadEnd = function () {
  8059. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8060. };
  8061. request.addEventListener("loadend", onLoadEnd);
  8062. var onReadyStateChange = function () {
  8063. if (aborted) {
  8064. return;
  8065. }
  8066. // In case of undefined state in some browsers.
  8067. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8068. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8069. request.removeEventListener("readystatechange", onReadyStateChange);
  8070. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8071. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8072. return;
  8073. }
  8074. var retryStrategy = Tools.DefaultRetryStrategy;
  8075. if (retryStrategy) {
  8076. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8077. if (waitTime !== -1) {
  8078. // Prevent the request from completing for retry.
  8079. request.removeEventListener("loadend", onLoadEnd);
  8080. request = new XMLHttpRequest();
  8081. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8082. return;
  8083. }
  8084. }
  8085. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8086. if (onError) {
  8087. onError(request, e);
  8088. }
  8089. else {
  8090. throw e;
  8091. }
  8092. }
  8093. };
  8094. request.addEventListener("readystatechange", onReadyStateChange);
  8095. request.send();
  8096. };
  8097. retryLoop(0);
  8098. };
  8099. // Caching all files
  8100. if (database && database.enableSceneOffline) {
  8101. var noIndexedDB_1 = function () {
  8102. if (!aborted) {
  8103. requestFile();
  8104. }
  8105. };
  8106. var loadFromIndexedDB = function () {
  8107. // TODO: database needs to support aborting and should return a IFileRequest
  8108. if (aborted) {
  8109. return;
  8110. }
  8111. if (database) {
  8112. database.loadFileFromDB(url, function (data) {
  8113. if (!aborted) {
  8114. onSuccess(data);
  8115. }
  8116. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8117. }, onProgress ? function (event) {
  8118. if (!aborted) {
  8119. onProgress(event);
  8120. }
  8121. } : undefined, noIndexedDB_1, useArrayBuffer);
  8122. }
  8123. };
  8124. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8125. }
  8126. else {
  8127. requestFile();
  8128. }
  8129. return fileRequest;
  8130. };
  8131. /**
  8132. * Load a script (identified by an url). When the url returns, the
  8133. * content of this file is added into a new script element, attached to the DOM (body element)
  8134. */
  8135. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8136. var head = document.getElementsByTagName('head')[0];
  8137. var script = document.createElement('script');
  8138. script.type = 'text/javascript';
  8139. script.src = scriptUrl;
  8140. script.onload = function () {
  8141. if (onSuccess) {
  8142. onSuccess();
  8143. }
  8144. };
  8145. script.onerror = function (e) {
  8146. if (onError) {
  8147. onError("Unable to load script", e);
  8148. }
  8149. };
  8150. head.appendChild(script);
  8151. };
  8152. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8153. var reader = new FileReader();
  8154. var request = {
  8155. onCompleteObservable: new BABYLON.Observable(),
  8156. abort: function () { return reader.abort(); },
  8157. };
  8158. reader.onloadend = function (e) {
  8159. request.onCompleteObservable.notifyObservers(request);
  8160. };
  8161. reader.onload = function (e) {
  8162. //target doesn't have result from ts 1.3
  8163. callback(e.target['result']);
  8164. };
  8165. reader.onprogress = progressCallback;
  8166. reader.readAsDataURL(fileToLoad);
  8167. return request;
  8168. };
  8169. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8170. var reader = new FileReader();
  8171. var request = {
  8172. onCompleteObservable: new BABYLON.Observable(),
  8173. abort: function () { return reader.abort(); },
  8174. };
  8175. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8176. reader.onerror = function (e) {
  8177. Tools.Log("Error while reading file: " + fileToLoad.name);
  8178. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8179. };
  8180. reader.onload = function (e) {
  8181. //target doesn't have result from ts 1.3
  8182. callback(e.target['result']);
  8183. };
  8184. if (progressCallBack) {
  8185. reader.onprogress = progressCallBack;
  8186. }
  8187. if (!useArrayBuffer) {
  8188. // Asynchronous read
  8189. reader.readAsText(fileToLoad);
  8190. }
  8191. else {
  8192. reader.readAsArrayBuffer(fileToLoad);
  8193. }
  8194. return request;
  8195. };
  8196. //returns a downloadable url to a file content.
  8197. Tools.FileAsURL = function (content) {
  8198. var fileBlob = new Blob([content]);
  8199. var url = window.URL || window.webkitURL;
  8200. var link = url.createObjectURL(fileBlob);
  8201. return link;
  8202. };
  8203. // Misc.
  8204. Tools.Format = function (value, decimals) {
  8205. if (decimals === void 0) { decimals = 2; }
  8206. return value.toFixed(decimals);
  8207. };
  8208. Tools.CheckExtends = function (v, min, max) {
  8209. if (v.x < min.x)
  8210. min.x = v.x;
  8211. if (v.y < min.y)
  8212. min.y = v.y;
  8213. if (v.z < min.z)
  8214. min.z = v.z;
  8215. if (v.x > max.x)
  8216. max.x = v.x;
  8217. if (v.y > max.y)
  8218. max.y = v.y;
  8219. if (v.z > max.z)
  8220. max.z = v.z;
  8221. };
  8222. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8223. for (var prop in source) {
  8224. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8225. continue;
  8226. }
  8227. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8228. continue;
  8229. }
  8230. var sourceValue = source[prop];
  8231. var typeOfSourceValue = typeof sourceValue;
  8232. if (typeOfSourceValue === "function") {
  8233. continue;
  8234. }
  8235. if (typeOfSourceValue === "object") {
  8236. if (sourceValue instanceof Array) {
  8237. destination[prop] = [];
  8238. if (sourceValue.length > 0) {
  8239. if (typeof sourceValue[0] == "object") {
  8240. for (var index = 0; index < sourceValue.length; index++) {
  8241. var clonedValue = cloneValue(sourceValue[index], destination);
  8242. if (destination[prop].indexOf(clonedValue) === -1) {
  8243. destination[prop].push(clonedValue);
  8244. }
  8245. }
  8246. }
  8247. else {
  8248. destination[prop] = sourceValue.slice(0);
  8249. }
  8250. }
  8251. }
  8252. else {
  8253. destination[prop] = cloneValue(sourceValue, destination);
  8254. }
  8255. }
  8256. else {
  8257. destination[prop] = sourceValue;
  8258. }
  8259. }
  8260. };
  8261. Tools.IsEmpty = function (obj) {
  8262. for (var i in obj) {
  8263. if (obj.hasOwnProperty(i)) {
  8264. return false;
  8265. }
  8266. }
  8267. return true;
  8268. };
  8269. Tools.RegisterTopRootEvents = function (events) {
  8270. for (var index = 0; index < events.length; index++) {
  8271. var event = events[index];
  8272. window.addEventListener(event.name, event.handler, false);
  8273. try {
  8274. if (window.parent) {
  8275. window.parent.addEventListener(event.name, event.handler, false);
  8276. }
  8277. }
  8278. catch (e) {
  8279. // Silently fails...
  8280. }
  8281. }
  8282. };
  8283. Tools.UnregisterTopRootEvents = function (events) {
  8284. for (var index = 0; index < events.length; index++) {
  8285. var event = events[index];
  8286. window.removeEventListener(event.name, event.handler);
  8287. try {
  8288. if (window.parent) {
  8289. window.parent.removeEventListener(event.name, event.handler);
  8290. }
  8291. }
  8292. catch (e) {
  8293. // Silently fails...
  8294. }
  8295. }
  8296. };
  8297. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8298. if (mimeType === void 0) { mimeType = "image/png"; }
  8299. // Read the contents of the framebuffer
  8300. var numberOfChannelsByLine = width * 4;
  8301. var halfHeight = height / 2;
  8302. //Reading datas from WebGL
  8303. var data = engine.readPixels(0, 0, width, height);
  8304. //To flip image on Y axis.
  8305. for (var i = 0; i < halfHeight; i++) {
  8306. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8307. var currentCell = j + i * numberOfChannelsByLine;
  8308. var targetLine = height - i - 1;
  8309. var targetCell = j + targetLine * numberOfChannelsByLine;
  8310. var temp = data[currentCell];
  8311. data[currentCell] = data[targetCell];
  8312. data[targetCell] = temp;
  8313. }
  8314. }
  8315. // Create a 2D canvas to store the result
  8316. if (!screenshotCanvas) {
  8317. screenshotCanvas = document.createElement('canvas');
  8318. }
  8319. screenshotCanvas.width = width;
  8320. screenshotCanvas.height = height;
  8321. var context = screenshotCanvas.getContext('2d');
  8322. if (context) {
  8323. // Copy the pixels to a 2D canvas
  8324. var imageData = context.createImageData(width, height);
  8325. var castData = (imageData.data);
  8326. castData.set(data);
  8327. context.putImageData(imageData, 0, 0);
  8328. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8329. }
  8330. };
  8331. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8332. if (mimeType === void 0) { mimeType = "image/png"; }
  8333. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8334. if (successCallback) {
  8335. successCallback(base64Image);
  8336. }
  8337. else {
  8338. // We need HTMLCanvasElement.toBlob for HD screenshots
  8339. if (!screenshotCanvas.toBlob) {
  8340. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8341. screenshotCanvas.toBlob = function (callback, type, quality) {
  8342. var _this = this;
  8343. setTimeout(function () {
  8344. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8345. for (var i = 0; i < len; i++) {
  8346. arr[i] = binStr.charCodeAt(i);
  8347. }
  8348. callback(new Blob([arr], { type: type || 'image/png' }));
  8349. });
  8350. };
  8351. }
  8352. screenshotCanvas.toBlob(function (blob) {
  8353. var url = URL.createObjectURL(blob);
  8354. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8355. if (("download" in document.createElement("a"))) {
  8356. var a = window.document.createElement("a");
  8357. a.href = url;
  8358. if (fileName) {
  8359. a.setAttribute("download", fileName);
  8360. }
  8361. else {
  8362. var date = new Date();
  8363. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8364. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8365. }
  8366. window.document.body.appendChild(a);
  8367. a.addEventListener("click", function () {
  8368. if (a.parentElement) {
  8369. a.parentElement.removeChild(a);
  8370. }
  8371. });
  8372. a.click();
  8373. }
  8374. else {
  8375. var newWindow = window.open("");
  8376. if (!newWindow)
  8377. return;
  8378. var img = newWindow.document.createElement("img");
  8379. img.onload = function () {
  8380. // no longer need to read the blob so it's revoked
  8381. URL.revokeObjectURL(url);
  8382. };
  8383. img.src = url;
  8384. newWindow.document.body.appendChild(img);
  8385. }
  8386. });
  8387. }
  8388. };
  8389. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8390. if (mimeType === void 0) { mimeType = "image/png"; }
  8391. var width;
  8392. var height;
  8393. // If a precision value is specified
  8394. if (size.precision) {
  8395. width = Math.round(engine.getRenderWidth() * size.precision);
  8396. height = Math.round(width / engine.getAspectRatio(camera));
  8397. }
  8398. else if (size.width && size.height) {
  8399. width = size.width;
  8400. height = size.height;
  8401. }
  8402. else if (size.width && !size.height) {
  8403. width = size.width;
  8404. height = Math.round(width / engine.getAspectRatio(camera));
  8405. }
  8406. else if (size.height && !size.width) {
  8407. height = size.height;
  8408. width = Math.round(height * engine.getAspectRatio(camera));
  8409. }
  8410. else if (!isNaN(size)) {
  8411. height = size;
  8412. width = size;
  8413. }
  8414. else {
  8415. Tools.Error("Invalid 'size' parameter !");
  8416. return;
  8417. }
  8418. if (!screenshotCanvas) {
  8419. screenshotCanvas = document.createElement('canvas');
  8420. }
  8421. screenshotCanvas.width = width;
  8422. screenshotCanvas.height = height;
  8423. var renderContext = screenshotCanvas.getContext("2d");
  8424. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8425. var newWidth = width;
  8426. var newHeight = newWidth / ratio;
  8427. if (newHeight > height) {
  8428. newHeight = height;
  8429. newWidth = newHeight * ratio;
  8430. }
  8431. var offsetX = Math.max(0, width - newWidth) / 2;
  8432. var offsetY = Math.max(0, height - newHeight) / 2;
  8433. var renderingCanvas = engine.getRenderingCanvas();
  8434. if (renderContext && renderingCanvas) {
  8435. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8436. }
  8437. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8438. };
  8439. /**
  8440. * Generates an image screenshot from the specified camera.
  8441. *
  8442. * @param engine The engine to use for rendering
  8443. * @param camera The camera to use for rendering
  8444. * @param size This parameter can be set to a single number or to an object with the
  8445. * following (optional) properties: precision, width, height. If a single number is passed,
  8446. * it will be used for both width and height. If an object is passed, the screenshot size
  8447. * will be derived from the parameters. The precision property is a multiplier allowing
  8448. * rendering at a higher or lower resolution.
  8449. * @param successCallback The callback receives a single parameter which contains the
  8450. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8451. * src parameter of an <img> to display it.
  8452. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8453. * Check your browser for supported MIME types.
  8454. * @param samples Texture samples (default: 1)
  8455. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8456. * @param fileName A name for for the downloaded file.
  8457. * @constructor
  8458. */
  8459. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8460. if (mimeType === void 0) { mimeType = "image/png"; }
  8461. if (samples === void 0) { samples = 1; }
  8462. if (antialiasing === void 0) { antialiasing = false; }
  8463. var width;
  8464. var height;
  8465. //If a precision value is specified
  8466. if (size.precision) {
  8467. width = Math.round(engine.getRenderWidth() * size.precision);
  8468. height = Math.round(width / engine.getAspectRatio(camera));
  8469. size = { width: width, height: height };
  8470. }
  8471. else if (size.width && size.height) {
  8472. width = size.width;
  8473. height = size.height;
  8474. }
  8475. else if (size.width && !size.height) {
  8476. width = size.width;
  8477. height = Math.round(width / engine.getAspectRatio(camera));
  8478. size = { width: width, height: height };
  8479. }
  8480. else if (size.height && !size.width) {
  8481. height = size.height;
  8482. width = Math.round(height * engine.getAspectRatio(camera));
  8483. size = { width: width, height: height };
  8484. }
  8485. else if (!isNaN(size)) {
  8486. height = size;
  8487. width = size;
  8488. }
  8489. else {
  8490. Tools.Error("Invalid 'size' parameter !");
  8491. return;
  8492. }
  8493. var scene = camera.getScene();
  8494. var previousCamera = null;
  8495. if (scene.activeCamera !== camera) {
  8496. previousCamera = scene.activeCamera;
  8497. scene.activeCamera = camera;
  8498. }
  8499. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8500. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8501. texture.renderList = null;
  8502. texture.samples = samples;
  8503. if (antialiasing) {
  8504. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8505. }
  8506. texture.onAfterRenderObservable.add(function () {
  8507. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8508. });
  8509. scene.incrementRenderId();
  8510. scene.resetCachedMaterial();
  8511. texture.render(true);
  8512. texture.dispose();
  8513. if (previousCamera) {
  8514. scene.activeCamera = previousCamera;
  8515. }
  8516. camera.getProjectionMatrix(true); // Force cache refresh;
  8517. };
  8518. // XHR response validator for local file scenario
  8519. Tools.ValidateXHRData = function (xhr, dataType) {
  8520. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8521. if (dataType === void 0) { dataType = 7; }
  8522. try {
  8523. if (dataType & 1) {
  8524. if (xhr.responseText && xhr.responseText.length > 0) {
  8525. return true;
  8526. }
  8527. else if (dataType === 1) {
  8528. return false;
  8529. }
  8530. }
  8531. if (dataType & 2) {
  8532. // Check header width and height since there is no "TGA" magic number
  8533. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8534. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8535. return true;
  8536. }
  8537. else if (dataType === 2) {
  8538. return false;
  8539. }
  8540. }
  8541. if (dataType & 4) {
  8542. // Check for the "DDS" magic number
  8543. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8544. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8545. return true;
  8546. }
  8547. else {
  8548. return false;
  8549. }
  8550. }
  8551. }
  8552. catch (e) {
  8553. // Global protection
  8554. }
  8555. return false;
  8556. };
  8557. /**
  8558. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8559. * Be aware Math.random() could cause collisions, but:
  8560. * "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"
  8561. */
  8562. Tools.RandomId = function () {
  8563. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8564. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8565. return v.toString(16);
  8566. });
  8567. };
  8568. /**
  8569. * Test if the given uri is a base64 string.
  8570. * @param uri The uri to test
  8571. * @return True if the uri is a base64 string or false otherwise.
  8572. */
  8573. Tools.IsBase64 = function (uri) {
  8574. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8575. };
  8576. /**
  8577. * Decode the given base64 uri.
  8578. * @param uri The uri to decode
  8579. * @return The decoded base64 data.
  8580. */
  8581. Tools.DecodeBase64 = function (uri) {
  8582. var decodedString = atob(uri.split(",")[1]);
  8583. var bufferLength = decodedString.length;
  8584. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8585. for (var i = 0; i < bufferLength; i++) {
  8586. bufferView[i] = decodedString.charCodeAt(i);
  8587. }
  8588. return bufferView.buffer;
  8589. };
  8590. Object.defineProperty(Tools, "NoneLogLevel", {
  8591. get: function () {
  8592. return Tools._NoneLogLevel;
  8593. },
  8594. enumerable: true,
  8595. configurable: true
  8596. });
  8597. Object.defineProperty(Tools, "MessageLogLevel", {
  8598. get: function () {
  8599. return Tools._MessageLogLevel;
  8600. },
  8601. enumerable: true,
  8602. configurable: true
  8603. });
  8604. Object.defineProperty(Tools, "WarningLogLevel", {
  8605. get: function () {
  8606. return Tools._WarningLogLevel;
  8607. },
  8608. enumerable: true,
  8609. configurable: true
  8610. });
  8611. Object.defineProperty(Tools, "ErrorLogLevel", {
  8612. get: function () {
  8613. return Tools._ErrorLogLevel;
  8614. },
  8615. enumerable: true,
  8616. configurable: true
  8617. });
  8618. Object.defineProperty(Tools, "AllLogLevel", {
  8619. get: function () {
  8620. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8621. },
  8622. enumerable: true,
  8623. configurable: true
  8624. });
  8625. Tools._AddLogEntry = function (entry) {
  8626. Tools._LogCache = entry + Tools._LogCache;
  8627. if (Tools.OnNewCacheEntry) {
  8628. Tools.OnNewCacheEntry(entry);
  8629. }
  8630. };
  8631. Tools._FormatMessage = function (message) {
  8632. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8633. var date = new Date();
  8634. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8635. };
  8636. Tools._LogDisabled = function (message) {
  8637. // nothing to do
  8638. };
  8639. Tools._LogEnabled = function (message) {
  8640. var formattedMessage = Tools._FormatMessage(message);
  8641. console.log("BJS - " + formattedMessage);
  8642. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8643. Tools._AddLogEntry(entry);
  8644. };
  8645. Tools._WarnDisabled = function (message) {
  8646. // nothing to do
  8647. };
  8648. Tools._WarnEnabled = function (message) {
  8649. var formattedMessage = Tools._FormatMessage(message);
  8650. console.warn("BJS - " + formattedMessage);
  8651. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8652. Tools._AddLogEntry(entry);
  8653. };
  8654. Tools._ErrorDisabled = function (message) {
  8655. // nothing to do
  8656. };
  8657. Tools._ErrorEnabled = function (message) {
  8658. Tools.errorsCount++;
  8659. var formattedMessage = Tools._FormatMessage(message);
  8660. console.error("BJS - " + formattedMessage);
  8661. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8662. Tools._AddLogEntry(entry);
  8663. };
  8664. Object.defineProperty(Tools, "LogCache", {
  8665. get: function () {
  8666. return Tools._LogCache;
  8667. },
  8668. enumerable: true,
  8669. configurable: true
  8670. });
  8671. Tools.ClearLogCache = function () {
  8672. Tools._LogCache = "";
  8673. Tools.errorsCount = 0;
  8674. };
  8675. Object.defineProperty(Tools, "LogLevels", {
  8676. set: function (level) {
  8677. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8678. Tools.Log = Tools._LogEnabled;
  8679. }
  8680. else {
  8681. Tools.Log = Tools._LogDisabled;
  8682. }
  8683. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8684. Tools.Warn = Tools._WarnEnabled;
  8685. }
  8686. else {
  8687. Tools.Warn = Tools._WarnDisabled;
  8688. }
  8689. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8690. Tools.Error = Tools._ErrorEnabled;
  8691. }
  8692. else {
  8693. Tools.Error = Tools._ErrorDisabled;
  8694. }
  8695. },
  8696. enumerable: true,
  8697. configurable: true
  8698. });
  8699. Tools.IsWindowObjectExist = function () {
  8700. return (typeof window) !== "undefined";
  8701. };
  8702. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8703. get: function () {
  8704. return Tools._PerformanceNoneLogLevel;
  8705. },
  8706. enumerable: true,
  8707. configurable: true
  8708. });
  8709. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8710. get: function () {
  8711. return Tools._PerformanceUserMarkLogLevel;
  8712. },
  8713. enumerable: true,
  8714. configurable: true
  8715. });
  8716. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8717. get: function () {
  8718. return Tools._PerformanceConsoleLogLevel;
  8719. },
  8720. enumerable: true,
  8721. configurable: true
  8722. });
  8723. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8724. set: function (level) {
  8725. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8726. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8727. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8728. return;
  8729. }
  8730. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8731. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8732. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8733. return;
  8734. }
  8735. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8736. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8737. },
  8738. enumerable: true,
  8739. configurable: true
  8740. });
  8741. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8742. };
  8743. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8744. };
  8745. Tools._StartUserMark = function (counterName, condition) {
  8746. if (condition === void 0) { condition = true; }
  8747. if (!Tools._performance) {
  8748. if (!Tools.IsWindowObjectExist()) {
  8749. return;
  8750. }
  8751. Tools._performance = window.performance;
  8752. }
  8753. if (!condition || !Tools._performance.mark) {
  8754. return;
  8755. }
  8756. Tools._performance.mark(counterName + "-Begin");
  8757. };
  8758. Tools._EndUserMark = function (counterName, condition) {
  8759. if (condition === void 0) { condition = true; }
  8760. if (!condition || !Tools._performance.mark) {
  8761. return;
  8762. }
  8763. Tools._performance.mark(counterName + "-End");
  8764. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8765. };
  8766. Tools._StartPerformanceConsole = function (counterName, condition) {
  8767. if (condition === void 0) { condition = true; }
  8768. if (!condition) {
  8769. return;
  8770. }
  8771. Tools._StartUserMark(counterName, condition);
  8772. if (console.time) {
  8773. console.time(counterName);
  8774. }
  8775. };
  8776. Tools._EndPerformanceConsole = function (counterName, condition) {
  8777. if (condition === void 0) { condition = true; }
  8778. if (!condition) {
  8779. return;
  8780. }
  8781. Tools._EndUserMark(counterName, condition);
  8782. if (console.time) {
  8783. console.timeEnd(counterName);
  8784. }
  8785. };
  8786. Object.defineProperty(Tools, "Now", {
  8787. get: function () {
  8788. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8789. return window.performance.now();
  8790. }
  8791. return new Date().getTime();
  8792. },
  8793. enumerable: true,
  8794. configurable: true
  8795. });
  8796. /**
  8797. * This method will return the name of the class used to create the instance of the given object.
  8798. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8799. * @param object the object to get the class name from
  8800. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8801. */
  8802. Tools.GetClassName = function (object, isType) {
  8803. if (isType === void 0) { isType = false; }
  8804. var name = null;
  8805. if (!isType && object.getClassName) {
  8806. name = object.getClassName();
  8807. }
  8808. else {
  8809. if (object instanceof Object) {
  8810. var classObj = isType ? object : Object.getPrototypeOf(object);
  8811. name = classObj.constructor["__bjsclassName__"];
  8812. }
  8813. if (!name) {
  8814. name = typeof object;
  8815. }
  8816. }
  8817. return name;
  8818. };
  8819. Tools.First = function (array, predicate) {
  8820. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8821. var el = array_1[_i];
  8822. if (predicate(el)) {
  8823. return el;
  8824. }
  8825. }
  8826. return null;
  8827. };
  8828. /**
  8829. * This method will return the name of the full name of the class, including its owning module (if any).
  8830. * 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).
  8831. * @param object the object to get the class name from
  8832. * @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.
  8833. */
  8834. Tools.getFullClassName = function (object, isType) {
  8835. if (isType === void 0) { isType = false; }
  8836. var className = null;
  8837. var moduleName = null;
  8838. if (!isType && object.getClassName) {
  8839. className = object.getClassName();
  8840. }
  8841. else {
  8842. if (object instanceof Object) {
  8843. var classObj = isType ? object : Object.getPrototypeOf(object);
  8844. className = classObj.constructor["__bjsclassName__"];
  8845. moduleName = classObj.constructor["__bjsmoduleName__"];
  8846. }
  8847. if (!className) {
  8848. className = typeof object;
  8849. }
  8850. }
  8851. if (!className) {
  8852. return null;
  8853. }
  8854. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8855. };
  8856. /**
  8857. * 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.
  8858. * @param array
  8859. */
  8860. Tools.arrayOrStringFeeder = function (array) {
  8861. return function (index) {
  8862. if (index >= array.length) {
  8863. return null;
  8864. }
  8865. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  8866. if (val && val.getHashCode) {
  8867. val = val.getHashCode();
  8868. }
  8869. if (typeof val === "string") {
  8870. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  8871. }
  8872. return val;
  8873. };
  8874. };
  8875. /**
  8876. * Compute the hashCode of a stream of number
  8877. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  8878. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  8879. * @return the hash code computed
  8880. */
  8881. Tools.hashCodeFromStream = function (feeder) {
  8882. // Based from here: http://stackoverflow.com/a/7616484/802124
  8883. var hash = 0;
  8884. var index = 0;
  8885. var chr = feeder(index++);
  8886. while (chr != null) {
  8887. hash = ((hash << 5) - hash) + chr;
  8888. hash |= 0; // Convert to 32bit integer
  8889. chr = feeder(index++);
  8890. }
  8891. return hash;
  8892. };
  8893. Tools.BaseUrl = "";
  8894. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  8895. /**
  8896. * Default behaviour for cors in the application.
  8897. * It can be a string if the expected behavior is identical in the entire app.
  8898. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  8899. */
  8900. Tools.CorsBehavior = "anonymous";
  8901. Tools.UseFallbackTexture = true;
  8902. /**
  8903. * Use this object to register external classes like custom textures or material
  8904. * to allow the laoders to instantiate them
  8905. */
  8906. Tools.RegisteredExternalClasses = {};
  8907. // Used in case of a texture loading problem
  8908. 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";
  8909. Tools.PreprocessUrl = function (url) {
  8910. return url;
  8911. };
  8912. // Logs
  8913. Tools._NoneLogLevel = 0;
  8914. Tools._MessageLogLevel = 1;
  8915. Tools._WarningLogLevel = 2;
  8916. Tools._ErrorLogLevel = 4;
  8917. Tools._LogCache = "";
  8918. Tools.errorsCount = 0;
  8919. Tools.Log = Tools._LogEnabled;
  8920. Tools.Warn = Tools._WarnEnabled;
  8921. Tools.Error = Tools._ErrorEnabled;
  8922. // Performances
  8923. Tools._PerformanceNoneLogLevel = 0;
  8924. Tools._PerformanceUserMarkLogLevel = 1;
  8925. Tools._PerformanceConsoleLogLevel = 2;
  8926. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8927. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8928. return Tools;
  8929. }());
  8930. BABYLON.Tools = Tools;
  8931. /**
  8932. * This class is used to track a performance counter which is number based.
  8933. * The user has access to many properties which give statistics of different nature
  8934. *
  8935. * The implementer can track two kinds of Performance Counter: time and count
  8936. * 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.
  8937. * 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.
  8938. */
  8939. var PerfCounter = /** @class */ (function () {
  8940. function PerfCounter() {
  8941. this._startMonitoringTime = 0;
  8942. this._min = 0;
  8943. this._max = 0;
  8944. this._average = 0;
  8945. this._lastSecAverage = 0;
  8946. this._current = 0;
  8947. this._totalValueCount = 0;
  8948. this._totalAccumulated = 0;
  8949. this._lastSecAccumulated = 0;
  8950. this._lastSecTime = 0;
  8951. this._lastSecValueCount = 0;
  8952. }
  8953. Object.defineProperty(PerfCounter.prototype, "min", {
  8954. /**
  8955. * Returns the smallest value ever
  8956. */
  8957. get: function () {
  8958. return this._min;
  8959. },
  8960. enumerable: true,
  8961. configurable: true
  8962. });
  8963. Object.defineProperty(PerfCounter.prototype, "max", {
  8964. /**
  8965. * Returns the biggest value ever
  8966. */
  8967. get: function () {
  8968. return this._max;
  8969. },
  8970. enumerable: true,
  8971. configurable: true
  8972. });
  8973. Object.defineProperty(PerfCounter.prototype, "average", {
  8974. /**
  8975. * Returns the average value since the performance counter is running
  8976. */
  8977. get: function () {
  8978. return this._average;
  8979. },
  8980. enumerable: true,
  8981. configurable: true
  8982. });
  8983. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  8984. /**
  8985. * Returns the average value of the last second the counter was monitored
  8986. */
  8987. get: function () {
  8988. return this._lastSecAverage;
  8989. },
  8990. enumerable: true,
  8991. configurable: true
  8992. });
  8993. Object.defineProperty(PerfCounter.prototype, "current", {
  8994. /**
  8995. * Returns the current value
  8996. */
  8997. get: function () {
  8998. return this._current;
  8999. },
  9000. enumerable: true,
  9001. configurable: true
  9002. });
  9003. Object.defineProperty(PerfCounter.prototype, "total", {
  9004. get: function () {
  9005. return this._totalAccumulated;
  9006. },
  9007. enumerable: true,
  9008. configurable: true
  9009. });
  9010. Object.defineProperty(PerfCounter.prototype, "count", {
  9011. get: function () {
  9012. return this._totalValueCount;
  9013. },
  9014. enumerable: true,
  9015. configurable: true
  9016. });
  9017. /**
  9018. * Call this method to start monitoring a new frame.
  9019. * 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.
  9020. */
  9021. PerfCounter.prototype.fetchNewFrame = function () {
  9022. this._totalValueCount++;
  9023. this._current = 0;
  9024. this._lastSecValueCount++;
  9025. };
  9026. /**
  9027. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9028. * @param newCount the count value to add to the monitored count
  9029. * @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.
  9030. */
  9031. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9032. if (!PerfCounter.Enabled) {
  9033. return;
  9034. }
  9035. this._current += newCount;
  9036. if (fetchResult) {
  9037. this._fetchResult();
  9038. }
  9039. };
  9040. /**
  9041. * Start monitoring this performance counter
  9042. */
  9043. PerfCounter.prototype.beginMonitoring = function () {
  9044. if (!PerfCounter.Enabled) {
  9045. return;
  9046. }
  9047. this._startMonitoringTime = Tools.Now;
  9048. };
  9049. /**
  9050. * Compute the time lapsed since the previous beginMonitoring() call.
  9051. * @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
  9052. */
  9053. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9054. if (newFrame === void 0) { newFrame = true; }
  9055. if (!PerfCounter.Enabled) {
  9056. return;
  9057. }
  9058. if (newFrame) {
  9059. this.fetchNewFrame();
  9060. }
  9061. var currentTime = Tools.Now;
  9062. this._current = currentTime - this._startMonitoringTime;
  9063. if (newFrame) {
  9064. this._fetchResult();
  9065. }
  9066. };
  9067. PerfCounter.prototype._fetchResult = function () {
  9068. this._totalAccumulated += this._current;
  9069. this._lastSecAccumulated += this._current;
  9070. // Min/Max update
  9071. this._min = Math.min(this._min, this._current);
  9072. this._max = Math.max(this._max, this._current);
  9073. this._average = this._totalAccumulated / this._totalValueCount;
  9074. // Reset last sec?
  9075. var now = Tools.Now;
  9076. if ((now - this._lastSecTime) > 1000) {
  9077. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9078. this._lastSecTime = now;
  9079. this._lastSecAccumulated = 0;
  9080. this._lastSecValueCount = 0;
  9081. }
  9082. };
  9083. PerfCounter.Enabled = true;
  9084. return PerfCounter;
  9085. }());
  9086. BABYLON.PerfCounter = PerfCounter;
  9087. /**
  9088. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9089. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9090. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9091. * @param name The name of the class, case should be preserved
  9092. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9093. */
  9094. function className(name, module) {
  9095. return function (target) {
  9096. target["__bjsclassName__"] = name;
  9097. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9098. };
  9099. }
  9100. BABYLON.className = className;
  9101. /**
  9102. * An implementation of a loop for asynchronous functions.
  9103. */
  9104. var AsyncLoop = /** @class */ (function () {
  9105. /**
  9106. * Constroctor.
  9107. * @param iterations the number of iterations.
  9108. * @param _fn the function to run each iteration
  9109. * @param _successCallback the callback that will be called upon succesful execution
  9110. * @param offset starting offset.
  9111. */
  9112. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9113. if (offset === void 0) { offset = 0; }
  9114. this.iterations = iterations;
  9115. this._fn = _fn;
  9116. this._successCallback = _successCallback;
  9117. this.index = offset - 1;
  9118. this._done = false;
  9119. }
  9120. /**
  9121. * Execute the next iteration. Must be called after the last iteration was finished.
  9122. */
  9123. AsyncLoop.prototype.executeNext = function () {
  9124. if (!this._done) {
  9125. if (this.index + 1 < this.iterations) {
  9126. ++this.index;
  9127. this._fn(this);
  9128. }
  9129. else {
  9130. this.breakLoop();
  9131. }
  9132. }
  9133. };
  9134. /**
  9135. * Break the loop and run the success callback.
  9136. */
  9137. AsyncLoop.prototype.breakLoop = function () {
  9138. this._done = true;
  9139. this._successCallback();
  9140. };
  9141. /**
  9142. * Helper function
  9143. */
  9144. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9145. if (offset === void 0) { offset = 0; }
  9146. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9147. loop.executeNext();
  9148. return loop;
  9149. };
  9150. /**
  9151. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9152. * @param iterations total number of iterations
  9153. * @param syncedIterations number of synchronous iterations in each async iteration.
  9154. * @param fn the function to call each iteration.
  9155. * @param callback a success call back that will be called when iterating stops.
  9156. * @param breakFunction a break condition (optional)
  9157. * @param timeout timeout settings for the setTimeout function. default - 0.
  9158. * @constructor
  9159. */
  9160. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9161. if (timeout === void 0) { timeout = 0; }
  9162. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9163. if (breakFunction && breakFunction())
  9164. loop.breakLoop();
  9165. else {
  9166. setTimeout(function () {
  9167. for (var i = 0; i < syncedIterations; ++i) {
  9168. var iteration = (loop.index * syncedIterations) + i;
  9169. if (iteration >= iterations)
  9170. break;
  9171. fn(iteration);
  9172. if (breakFunction && breakFunction()) {
  9173. loop.breakLoop();
  9174. break;
  9175. }
  9176. }
  9177. loop.executeNext();
  9178. }, timeout);
  9179. }
  9180. }, callback);
  9181. };
  9182. return AsyncLoop;
  9183. }());
  9184. BABYLON.AsyncLoop = AsyncLoop;
  9185. })(BABYLON || (BABYLON = {}));
  9186. //# sourceMappingURL=babylon.tools.js.map
  9187. var BABYLON;
  9188. (function (BABYLON) {
  9189. var PromiseStates;
  9190. (function (PromiseStates) {
  9191. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9192. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9193. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9194. })(PromiseStates || (PromiseStates = {}));
  9195. var FulFillmentAgregator = /** @class */ (function () {
  9196. function FulFillmentAgregator() {
  9197. this.count = 0;
  9198. this.target = 0;
  9199. this.results = [];
  9200. }
  9201. return FulFillmentAgregator;
  9202. }());
  9203. var InternalPromise = /** @class */ (function () {
  9204. function InternalPromise(resolver) {
  9205. var _this = this;
  9206. this._state = PromiseStates.Pending;
  9207. this._children = new Array();
  9208. this._rejectWasConsumed = false;
  9209. if (!resolver) {
  9210. return;
  9211. }
  9212. try {
  9213. resolver(function (value) {
  9214. _this._resolve(value);
  9215. }, function (reason) {
  9216. _this._reject(reason);
  9217. });
  9218. }
  9219. catch (e) {
  9220. this._reject(e.message);
  9221. }
  9222. }
  9223. Object.defineProperty(InternalPromise.prototype, "state", {
  9224. get: function () {
  9225. return this._state;
  9226. },
  9227. enumerable: true,
  9228. configurable: true
  9229. });
  9230. Object.defineProperty(InternalPromise.prototype, "isFulfilled", {
  9231. get: function () {
  9232. return this._state === PromiseStates.Fulfilled;
  9233. },
  9234. enumerable: true,
  9235. configurable: true
  9236. });
  9237. Object.defineProperty(InternalPromise.prototype, "isRejected", {
  9238. get: function () {
  9239. return this._state === PromiseStates.Rejected;
  9240. },
  9241. enumerable: true,
  9242. configurable: true
  9243. });
  9244. Object.defineProperty(InternalPromise.prototype, "isPending", {
  9245. get: function () {
  9246. return this._state === PromiseStates.Pending;
  9247. },
  9248. enumerable: true,
  9249. configurable: true
  9250. });
  9251. InternalPromise.prototype.value = function () {
  9252. if (!this.isFulfilled) {
  9253. throw new Error("Promise is not fulfilled");
  9254. }
  9255. return this._result;
  9256. };
  9257. InternalPromise.prototype.reason = function () {
  9258. if (!this.isRejected) {
  9259. throw new Error("Promise is not rejected");
  9260. }
  9261. return this._reason;
  9262. };
  9263. InternalPromise.prototype.catch = function (onRejected) {
  9264. return this.then(undefined, onRejected);
  9265. };
  9266. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9267. var newPromise = new InternalPromise();
  9268. newPromise._onFulfilled = onFulfilled;
  9269. newPromise._onRejected = onRejected;
  9270. // Composition
  9271. this._children.push(newPromise);
  9272. if (this._state !== PromiseStates.Pending) {
  9273. if (this._state === PromiseStates.Fulfilled || this._rejectWasConsumed) {
  9274. var returnedValue = newPromise._resolve(this._result);
  9275. if (returnedValue !== undefined && returnedValue !== null) {
  9276. if (returnedValue._state !== undefined) {
  9277. var returnedPromise = returnedValue;
  9278. newPromise._children.push(returnedPromise);
  9279. newPromise = returnedPromise;
  9280. }
  9281. else {
  9282. newPromise._result = returnedValue;
  9283. }
  9284. }
  9285. }
  9286. else {
  9287. newPromise._reject(this._reason);
  9288. }
  9289. }
  9290. return newPromise;
  9291. };
  9292. InternalPromise.prototype._moveChildren = function (children) {
  9293. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9294. if (this.isFulfilled) {
  9295. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9296. var child = _b[_i];
  9297. child._resolve(this._result);
  9298. }
  9299. }
  9300. else if (this.isRejected) {
  9301. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9302. var child = _d[_c];
  9303. child._reject(this._reason);
  9304. }
  9305. }
  9306. var _a;
  9307. };
  9308. InternalPromise.prototype._resolve = function (value) {
  9309. try {
  9310. this._state = PromiseStates.Fulfilled;
  9311. this._result = value;
  9312. var returnedValue = null;
  9313. if (this._onFulfilled) {
  9314. returnedValue = this._onFulfilled(value);
  9315. }
  9316. if (returnedValue !== undefined && returnedValue !== null) {
  9317. if (returnedValue._state !== undefined) {
  9318. // Transmit children
  9319. var returnedPromise = returnedValue;
  9320. returnedPromise._moveChildren(this._children);
  9321. }
  9322. else {
  9323. value = returnedValue;
  9324. }
  9325. }
  9326. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9327. var child = _a[_i];
  9328. child._resolve(value);
  9329. }
  9330. return returnedValue;
  9331. }
  9332. catch (e) {
  9333. this._reject(e.message);
  9334. }
  9335. return null;
  9336. };
  9337. InternalPromise.prototype._reject = function (reason) {
  9338. this._state = PromiseStates.Rejected;
  9339. this._reason = reason;
  9340. if (this._onRejected) {
  9341. this._onRejected(reason);
  9342. this._rejectWasConsumed = true;
  9343. }
  9344. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9345. var child = _a[_i];
  9346. if (this._rejectWasConsumed) {
  9347. child._resolve(null);
  9348. }
  9349. else {
  9350. child._reject(reason);
  9351. }
  9352. }
  9353. };
  9354. InternalPromise.resolve = function (value) {
  9355. var newPromise = new InternalPromise();
  9356. newPromise._resolve(value);
  9357. return newPromise;
  9358. };
  9359. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9360. promise.then(function (value) {
  9361. agregator.results[index] = value;
  9362. agregator.count++;
  9363. if (agregator.count === agregator.target) {
  9364. agregator.rootPromise._resolve(agregator.results);
  9365. }
  9366. return null;
  9367. }, function (reason) {
  9368. if (!agregator.rootPromise.isRejected) {
  9369. agregator.rootPromise._reject(reason);
  9370. }
  9371. });
  9372. };
  9373. InternalPromise.all = function (promises) {
  9374. var newPromise = new InternalPromise();
  9375. var agregator = new FulFillmentAgregator();
  9376. agregator.target = promises.length;
  9377. agregator.rootPromise = newPromise;
  9378. if (promises.length) {
  9379. for (var index = 0; index < promises.length; index++) {
  9380. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9381. }
  9382. }
  9383. else {
  9384. newPromise._resolve([]);
  9385. }
  9386. return newPromise;
  9387. };
  9388. return InternalPromise;
  9389. }());
  9390. /**
  9391. * Helper class that provides a small promise polyfill
  9392. */
  9393. var PromisePolyfill = /** @class */ (function () {
  9394. function PromisePolyfill() {
  9395. }
  9396. /**
  9397. * Static function used to check if the polyfill is required
  9398. * If this is the case then the function will inject the polyfill to window.Promise
  9399. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9400. */
  9401. PromisePolyfill.Apply = function (force) {
  9402. if (force === void 0) { force = false; }
  9403. if (force || typeof Promise === 'undefined') {
  9404. var root = window;
  9405. root.Promise = InternalPromise;
  9406. }
  9407. };
  9408. return PromisePolyfill;
  9409. }());
  9410. BABYLON.PromisePolyfill = PromisePolyfill;
  9411. })(BABYLON || (BABYLON = {}));
  9412. //# sourceMappingURL=babylon.promise.js.map
  9413. var BABYLON;
  9414. (function (BABYLON) {
  9415. var _AlphaState = /** @class */ (function () {
  9416. /**
  9417. * Initializes the state.
  9418. */
  9419. function _AlphaState() {
  9420. this._isAlphaBlendDirty = false;
  9421. this._isBlendFunctionParametersDirty = false;
  9422. this._isBlendEquationParametersDirty = false;
  9423. this._isBlendConstantsDirty = false;
  9424. this._alphaBlend = false;
  9425. this._blendFunctionParameters = new Array(4);
  9426. this._blendEquationParameters = new Array(2);
  9427. this._blendConstants = new Array(4);
  9428. this.reset();
  9429. }
  9430. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9431. get: function () {
  9432. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9433. },
  9434. enumerable: true,
  9435. configurable: true
  9436. });
  9437. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9438. get: function () {
  9439. return this._alphaBlend;
  9440. },
  9441. set: function (value) {
  9442. if (this._alphaBlend === value) {
  9443. return;
  9444. }
  9445. this._alphaBlend = value;
  9446. this._isAlphaBlendDirty = true;
  9447. },
  9448. enumerable: true,
  9449. configurable: true
  9450. });
  9451. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9452. if (this._blendConstants[0] === r &&
  9453. this._blendConstants[1] === g &&
  9454. this._blendConstants[2] === b &&
  9455. this._blendConstants[3] === a) {
  9456. return;
  9457. }
  9458. this._blendConstants[0] = r;
  9459. this._blendConstants[1] = g;
  9460. this._blendConstants[2] = b;
  9461. this._blendConstants[3] = a;
  9462. this._isBlendConstantsDirty = true;
  9463. };
  9464. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9465. if (this._blendFunctionParameters[0] === value0 &&
  9466. this._blendFunctionParameters[1] === value1 &&
  9467. this._blendFunctionParameters[2] === value2 &&
  9468. this._blendFunctionParameters[3] === value3) {
  9469. return;
  9470. }
  9471. this._blendFunctionParameters[0] = value0;
  9472. this._blendFunctionParameters[1] = value1;
  9473. this._blendFunctionParameters[2] = value2;
  9474. this._blendFunctionParameters[3] = value3;
  9475. this._isBlendFunctionParametersDirty = true;
  9476. };
  9477. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9478. if (this._blendEquationParameters[0] === rgb &&
  9479. this._blendEquationParameters[1] === alpha) {
  9480. return;
  9481. }
  9482. this._blendEquationParameters[0] = rgb;
  9483. this._blendEquationParameters[1] = alpha;
  9484. this._isBlendEquationParametersDirty = true;
  9485. };
  9486. _AlphaState.prototype.reset = function () {
  9487. this._alphaBlend = false;
  9488. this._blendFunctionParameters[0] = null;
  9489. this._blendFunctionParameters[1] = null;
  9490. this._blendFunctionParameters[2] = null;
  9491. this._blendFunctionParameters[3] = null;
  9492. this._blendEquationParameters[0] = null;
  9493. this._blendEquationParameters[1] = null;
  9494. this._blendConstants[0] = null;
  9495. this._blendConstants[1] = null;
  9496. this._blendConstants[2] = null;
  9497. this._blendConstants[3] = null;
  9498. this._isAlphaBlendDirty = true;
  9499. this._isBlendFunctionParametersDirty = false;
  9500. this._isBlendEquationParametersDirty = false;
  9501. this._isBlendConstantsDirty = false;
  9502. };
  9503. _AlphaState.prototype.apply = function (gl) {
  9504. if (!this.isDirty) {
  9505. return;
  9506. }
  9507. // Alpha blend
  9508. if (this._isAlphaBlendDirty) {
  9509. if (this._alphaBlend) {
  9510. gl.enable(gl.BLEND);
  9511. }
  9512. else {
  9513. gl.disable(gl.BLEND);
  9514. }
  9515. this._isAlphaBlendDirty = false;
  9516. }
  9517. // Alpha function
  9518. if (this._isBlendFunctionParametersDirty) {
  9519. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9520. this._isBlendFunctionParametersDirty = false;
  9521. }
  9522. // Alpha equation
  9523. if (this._isBlendEquationParametersDirty) {
  9524. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9525. this._isBlendEquationParametersDirty = false;
  9526. }
  9527. // Constants
  9528. if (this._isBlendConstantsDirty) {
  9529. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9530. this._isBlendConstantsDirty = false;
  9531. }
  9532. };
  9533. return _AlphaState;
  9534. }());
  9535. BABYLON._AlphaState = _AlphaState;
  9536. })(BABYLON || (BABYLON = {}));
  9537. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9538. var BABYLON;
  9539. (function (BABYLON) {
  9540. var _DepthCullingState = /** @class */ (function () {
  9541. /**
  9542. * Initializes the state.
  9543. */
  9544. function _DepthCullingState() {
  9545. this._isDepthTestDirty = false;
  9546. this._isDepthMaskDirty = false;
  9547. this._isDepthFuncDirty = false;
  9548. this._isCullFaceDirty = false;
  9549. this._isCullDirty = false;
  9550. this._isZOffsetDirty = false;
  9551. this._isFrontFaceDirty = false;
  9552. this.reset();
  9553. }
  9554. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9555. get: function () {
  9556. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9557. },
  9558. enumerable: true,
  9559. configurable: true
  9560. });
  9561. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9562. get: function () {
  9563. return this._zOffset;
  9564. },
  9565. set: function (value) {
  9566. if (this._zOffset === value) {
  9567. return;
  9568. }
  9569. this._zOffset = value;
  9570. this._isZOffsetDirty = true;
  9571. },
  9572. enumerable: true,
  9573. configurable: true
  9574. });
  9575. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9576. get: function () {
  9577. return this._cullFace;
  9578. },
  9579. set: function (value) {
  9580. if (this._cullFace === value) {
  9581. return;
  9582. }
  9583. this._cullFace = value;
  9584. this._isCullFaceDirty = true;
  9585. },
  9586. enumerable: true,
  9587. configurable: true
  9588. });
  9589. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9590. get: function () {
  9591. return this._cull;
  9592. },
  9593. set: function (value) {
  9594. if (this._cull === value) {
  9595. return;
  9596. }
  9597. this._cull = value;
  9598. this._isCullDirty = true;
  9599. },
  9600. enumerable: true,
  9601. configurable: true
  9602. });
  9603. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9604. get: function () {
  9605. return this._depthFunc;
  9606. },
  9607. set: function (value) {
  9608. if (this._depthFunc === value) {
  9609. return;
  9610. }
  9611. this._depthFunc = value;
  9612. this._isDepthFuncDirty = true;
  9613. },
  9614. enumerable: true,
  9615. configurable: true
  9616. });
  9617. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9618. get: function () {
  9619. return this._depthMask;
  9620. },
  9621. set: function (value) {
  9622. if (this._depthMask === value) {
  9623. return;
  9624. }
  9625. this._depthMask = value;
  9626. this._isDepthMaskDirty = true;
  9627. },
  9628. enumerable: true,
  9629. configurable: true
  9630. });
  9631. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9632. get: function () {
  9633. return this._depthTest;
  9634. },
  9635. set: function (value) {
  9636. if (this._depthTest === value) {
  9637. return;
  9638. }
  9639. this._depthTest = value;
  9640. this._isDepthTestDirty = true;
  9641. },
  9642. enumerable: true,
  9643. configurable: true
  9644. });
  9645. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9646. get: function () {
  9647. return this._frontFace;
  9648. },
  9649. set: function (value) {
  9650. if (this._frontFace === value) {
  9651. return;
  9652. }
  9653. this._frontFace = value;
  9654. this._isFrontFaceDirty = true;
  9655. },
  9656. enumerable: true,
  9657. configurable: true
  9658. });
  9659. _DepthCullingState.prototype.reset = function () {
  9660. this._depthMask = true;
  9661. this._depthTest = true;
  9662. this._depthFunc = null;
  9663. this._cullFace = null;
  9664. this._cull = null;
  9665. this._zOffset = 0;
  9666. this._frontFace = null;
  9667. this._isDepthTestDirty = true;
  9668. this._isDepthMaskDirty = true;
  9669. this._isDepthFuncDirty = false;
  9670. this._isCullFaceDirty = false;
  9671. this._isCullDirty = false;
  9672. this._isZOffsetDirty = false;
  9673. this._isFrontFaceDirty = false;
  9674. };
  9675. _DepthCullingState.prototype.apply = function (gl) {
  9676. if (!this.isDirty) {
  9677. return;
  9678. }
  9679. // Cull
  9680. if (this._isCullDirty) {
  9681. if (this.cull) {
  9682. gl.enable(gl.CULL_FACE);
  9683. }
  9684. else {
  9685. gl.disable(gl.CULL_FACE);
  9686. }
  9687. this._isCullDirty = false;
  9688. }
  9689. // Cull face
  9690. if (this._isCullFaceDirty) {
  9691. gl.cullFace(this.cullFace);
  9692. this._isCullFaceDirty = false;
  9693. }
  9694. // Depth mask
  9695. if (this._isDepthMaskDirty) {
  9696. gl.depthMask(this.depthMask);
  9697. this._isDepthMaskDirty = false;
  9698. }
  9699. // Depth test
  9700. if (this._isDepthTestDirty) {
  9701. if (this.depthTest) {
  9702. gl.enable(gl.DEPTH_TEST);
  9703. }
  9704. else {
  9705. gl.disable(gl.DEPTH_TEST);
  9706. }
  9707. this._isDepthTestDirty = false;
  9708. }
  9709. // Depth func
  9710. if (this._isDepthFuncDirty) {
  9711. gl.depthFunc(this.depthFunc);
  9712. this._isDepthFuncDirty = false;
  9713. }
  9714. // zOffset
  9715. if (this._isZOffsetDirty) {
  9716. if (this.zOffset) {
  9717. gl.enable(gl.POLYGON_OFFSET_FILL);
  9718. gl.polygonOffset(this.zOffset, 0);
  9719. }
  9720. else {
  9721. gl.disable(gl.POLYGON_OFFSET_FILL);
  9722. }
  9723. this._isZOffsetDirty = false;
  9724. }
  9725. // Front face
  9726. if (this._isFrontFaceDirty) {
  9727. gl.frontFace(this.frontFace);
  9728. this._isFrontFaceDirty = false;
  9729. }
  9730. };
  9731. return _DepthCullingState;
  9732. }());
  9733. BABYLON._DepthCullingState = _DepthCullingState;
  9734. })(BABYLON || (BABYLON = {}));
  9735. //# sourceMappingURL=babylon.depthCullingState.js.map
  9736. var BABYLON;
  9737. (function (BABYLON) {
  9738. var _StencilState = /** @class */ (function () {
  9739. function _StencilState() {
  9740. this._isStencilTestDirty = false;
  9741. this._isStencilMaskDirty = false;
  9742. this._isStencilFuncDirty = false;
  9743. this._isStencilOpDirty = false;
  9744. this.reset();
  9745. }
  9746. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9747. get: function () {
  9748. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9749. },
  9750. enumerable: true,
  9751. configurable: true
  9752. });
  9753. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9754. get: function () {
  9755. return this._stencilFunc;
  9756. },
  9757. set: function (value) {
  9758. if (this._stencilFunc === value) {
  9759. return;
  9760. }
  9761. this._stencilFunc = value;
  9762. this._isStencilFuncDirty = true;
  9763. },
  9764. enumerable: true,
  9765. configurable: true
  9766. });
  9767. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9768. get: function () {
  9769. return this._stencilFuncRef;
  9770. },
  9771. set: function (value) {
  9772. if (this._stencilFuncRef === value) {
  9773. return;
  9774. }
  9775. this._stencilFuncRef = value;
  9776. this._isStencilFuncDirty = true;
  9777. },
  9778. enumerable: true,
  9779. configurable: true
  9780. });
  9781. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9782. get: function () {
  9783. return this._stencilFuncMask;
  9784. },
  9785. set: function (value) {
  9786. if (this._stencilFuncMask === value) {
  9787. return;
  9788. }
  9789. this._stencilFuncMask = value;
  9790. this._isStencilFuncDirty = true;
  9791. },
  9792. enumerable: true,
  9793. configurable: true
  9794. });
  9795. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9796. get: function () {
  9797. return this._stencilOpStencilFail;
  9798. },
  9799. set: function (value) {
  9800. if (this._stencilOpStencilFail === value) {
  9801. return;
  9802. }
  9803. this._stencilOpStencilFail = value;
  9804. this._isStencilOpDirty = true;
  9805. },
  9806. enumerable: true,
  9807. configurable: true
  9808. });
  9809. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9810. get: function () {
  9811. return this._stencilOpDepthFail;
  9812. },
  9813. set: function (value) {
  9814. if (this._stencilOpDepthFail === value) {
  9815. return;
  9816. }
  9817. this._stencilOpDepthFail = value;
  9818. this._isStencilOpDirty = true;
  9819. },
  9820. enumerable: true,
  9821. configurable: true
  9822. });
  9823. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9824. get: function () {
  9825. return this._stencilOpStencilDepthPass;
  9826. },
  9827. set: function (value) {
  9828. if (this._stencilOpStencilDepthPass === value) {
  9829. return;
  9830. }
  9831. this._stencilOpStencilDepthPass = value;
  9832. this._isStencilOpDirty = true;
  9833. },
  9834. enumerable: true,
  9835. configurable: true
  9836. });
  9837. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9838. get: function () {
  9839. return this._stencilMask;
  9840. },
  9841. set: function (value) {
  9842. if (this._stencilMask === value) {
  9843. return;
  9844. }
  9845. this._stencilMask = value;
  9846. this._isStencilMaskDirty = true;
  9847. },
  9848. enumerable: true,
  9849. configurable: true
  9850. });
  9851. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  9852. get: function () {
  9853. return this._stencilTest;
  9854. },
  9855. set: function (value) {
  9856. if (this._stencilTest === value) {
  9857. return;
  9858. }
  9859. this._stencilTest = value;
  9860. this._isStencilTestDirty = true;
  9861. },
  9862. enumerable: true,
  9863. configurable: true
  9864. });
  9865. _StencilState.prototype.reset = function () {
  9866. this._stencilTest = false;
  9867. this._stencilMask = 0xFF;
  9868. this._stencilFunc = BABYLON.Engine.ALWAYS;
  9869. this._stencilFuncRef = 1;
  9870. this._stencilFuncMask = 0xFF;
  9871. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  9872. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  9873. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  9874. this._isStencilTestDirty = true;
  9875. this._isStencilMaskDirty = true;
  9876. this._isStencilFuncDirty = true;
  9877. this._isStencilOpDirty = true;
  9878. };
  9879. _StencilState.prototype.apply = function (gl) {
  9880. if (!this.isDirty) {
  9881. return;
  9882. }
  9883. // Stencil test
  9884. if (this._isStencilTestDirty) {
  9885. if (this.stencilTest) {
  9886. gl.enable(gl.STENCIL_TEST);
  9887. }
  9888. else {
  9889. gl.disable(gl.STENCIL_TEST);
  9890. }
  9891. this._isStencilTestDirty = false;
  9892. }
  9893. // Stencil mask
  9894. if (this._isStencilMaskDirty) {
  9895. gl.stencilMask(this.stencilMask);
  9896. this._isStencilMaskDirty = false;
  9897. }
  9898. // Stencil func
  9899. if (this._isStencilFuncDirty) {
  9900. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  9901. this._isStencilFuncDirty = false;
  9902. }
  9903. // Stencil op
  9904. if (this._isStencilOpDirty) {
  9905. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  9906. this._isStencilOpDirty = false;
  9907. }
  9908. };
  9909. return _StencilState;
  9910. }());
  9911. BABYLON._StencilState = _StencilState;
  9912. })(BABYLON || (BABYLON = {}));
  9913. //# sourceMappingURL=babylon.stencilState.js.map
  9914. var BABYLON;
  9915. (function (BABYLON) {
  9916. var compileShader = function (gl, source, type, defines, shaderVersion) {
  9917. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  9918. };
  9919. var compileRawShader = function (gl, source, type) {
  9920. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  9921. gl.shaderSource(shader, source);
  9922. gl.compileShader(shader);
  9923. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  9924. var log = gl.getShaderInfoLog(shader);
  9925. if (log) {
  9926. throw new Error(log);
  9927. }
  9928. }
  9929. if (!shader) {
  9930. throw new Error("Something went wrong while compile the shader.");
  9931. }
  9932. return shader;
  9933. };
  9934. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  9935. var magFilter = gl.NEAREST;
  9936. var minFilter = gl.NEAREST;
  9937. switch (samplingMode) {
  9938. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  9939. magFilter = gl.LINEAR;
  9940. if (generateMipMaps) {
  9941. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  9942. }
  9943. else {
  9944. minFilter = gl.LINEAR;
  9945. }
  9946. break;
  9947. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  9948. magFilter = gl.LINEAR;
  9949. if (generateMipMaps) {
  9950. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  9951. }
  9952. else {
  9953. minFilter = gl.LINEAR;
  9954. }
  9955. break;
  9956. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  9957. magFilter = gl.NEAREST;
  9958. if (generateMipMaps) {
  9959. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  9960. }
  9961. else {
  9962. minFilter = gl.NEAREST;
  9963. }
  9964. break;
  9965. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  9966. magFilter = gl.NEAREST;
  9967. if (generateMipMaps) {
  9968. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  9969. }
  9970. else {
  9971. minFilter = gl.NEAREST;
  9972. }
  9973. break;
  9974. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  9975. magFilter = gl.NEAREST;
  9976. if (generateMipMaps) {
  9977. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  9978. }
  9979. else {
  9980. minFilter = gl.LINEAR;
  9981. }
  9982. break;
  9983. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  9984. magFilter = gl.NEAREST;
  9985. if (generateMipMaps) {
  9986. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  9987. }
  9988. else {
  9989. minFilter = gl.LINEAR;
  9990. }
  9991. break;
  9992. case BABYLON.Texture.NEAREST_LINEAR:
  9993. magFilter = gl.NEAREST;
  9994. minFilter = gl.LINEAR;
  9995. break;
  9996. case BABYLON.Texture.NEAREST_NEAREST:
  9997. magFilter = gl.NEAREST;
  9998. minFilter = gl.NEAREST;
  9999. break;
  10000. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10001. magFilter = gl.LINEAR;
  10002. if (generateMipMaps) {
  10003. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10004. }
  10005. else {
  10006. minFilter = gl.NEAREST;
  10007. }
  10008. break;
  10009. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10010. magFilter = gl.LINEAR;
  10011. if (generateMipMaps) {
  10012. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10013. }
  10014. else {
  10015. minFilter = gl.NEAREST;
  10016. }
  10017. break;
  10018. case BABYLON.Texture.LINEAR_LINEAR:
  10019. magFilter = gl.LINEAR;
  10020. minFilter = gl.LINEAR;
  10021. break;
  10022. case BABYLON.Texture.LINEAR_NEAREST:
  10023. magFilter = gl.LINEAR;
  10024. minFilter = gl.NEAREST;
  10025. break;
  10026. }
  10027. return {
  10028. min: minFilter,
  10029. mag: magFilter
  10030. };
  10031. };
  10032. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10033. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10034. var img;
  10035. var onload = function () {
  10036. loadedImages[index] = img;
  10037. loadedImages._internalCount++;
  10038. if (scene) {
  10039. scene._removePendingData(img);
  10040. }
  10041. if (loadedImages._internalCount === 6) {
  10042. onfinish(loadedImages);
  10043. }
  10044. };
  10045. var onerror = function (message, exception) {
  10046. if (scene) {
  10047. scene._removePendingData(img);
  10048. }
  10049. if (onErrorCallBack) {
  10050. onErrorCallBack(message, exception);
  10051. }
  10052. };
  10053. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10054. if (scene) {
  10055. scene._addPendingData(img);
  10056. }
  10057. };
  10058. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10059. if (onError === void 0) { onError = null; }
  10060. var loadedImages = [];
  10061. loadedImages._internalCount = 0;
  10062. for (var index = 0; index < 6; index++) {
  10063. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10064. }
  10065. };
  10066. var BufferPointer = /** @class */ (function () {
  10067. function BufferPointer() {
  10068. }
  10069. return BufferPointer;
  10070. }());
  10071. var InstancingAttributeInfo = /** @class */ (function () {
  10072. function InstancingAttributeInfo() {
  10073. }
  10074. return InstancingAttributeInfo;
  10075. }());
  10076. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10077. /**
  10078. * Define options used to create a render target texture
  10079. */
  10080. var RenderTargetCreationOptions = /** @class */ (function () {
  10081. function RenderTargetCreationOptions() {
  10082. }
  10083. return RenderTargetCreationOptions;
  10084. }());
  10085. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10086. /**
  10087. * Regroup several parameters relative to the browser in use
  10088. */
  10089. var EngineCapabilities = /** @class */ (function () {
  10090. function EngineCapabilities() {
  10091. }
  10092. return EngineCapabilities;
  10093. }());
  10094. BABYLON.EngineCapabilities = EngineCapabilities;
  10095. /**
  10096. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10097. */
  10098. var Engine = /** @class */ (function () {
  10099. /**
  10100. * @constructor
  10101. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10102. * @param antialias defines enable antialiasing (default: false)
  10103. * @param options defines further options to be sent to the getContext() function
  10104. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10105. */
  10106. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10107. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10108. var _this = this;
  10109. // Public members
  10110. this.forcePOTTextures = false;
  10111. this.isFullscreen = false;
  10112. this.isPointerLock = false;
  10113. this.cullBackFaces = true;
  10114. this.renderEvenInBackground = true;
  10115. this.preventCacheWipeBetweenFrames = false;
  10116. // To enable/disable IDB support and avoid XHR on .manifest
  10117. this.enableOfflineSupport = false;
  10118. this.scenes = new Array();
  10119. this.postProcesses = new Array();
  10120. // Observables
  10121. /**
  10122. * Observable event triggered each time the rendering canvas is resized
  10123. */
  10124. this.onResizeObservable = new BABYLON.Observable();
  10125. /**
  10126. * Observable event triggered each time the canvas loses focus
  10127. */
  10128. this.onCanvasBlurObservable = new BABYLON.Observable();
  10129. /**
  10130. * Observable event triggered each time the canvas gains focus
  10131. */
  10132. this.onCanvasFocusObservable = new BABYLON.Observable();
  10133. /**
  10134. * Observable event triggered each time the canvas receives pointerout event
  10135. */
  10136. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10137. /**
  10138. * Observable event triggered before each texture is initialized
  10139. */
  10140. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10141. //WebVR
  10142. this._vrDisplay = undefined;
  10143. this._vrSupported = false;
  10144. this._vrExclusivePointerMode = false;
  10145. // Uniform buffers list
  10146. this.disableUniformBuffers = false;
  10147. this._uniformBuffers = new Array();
  10148. // Observables
  10149. /**
  10150. * Observable raised when the engine begins a new frame
  10151. */
  10152. this.onBeginFrameObservable = new BABYLON.Observable();
  10153. /**
  10154. * Observable raised when the engine ends the current frame
  10155. */
  10156. this.onEndFrameObservable = new BABYLON.Observable();
  10157. /**
  10158. * Observable raised when the engine is about to compile a shader
  10159. */
  10160. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10161. /**
  10162. * Observable raised when the engine has jsut compiled a shader
  10163. */
  10164. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10165. this._windowIsBackground = false;
  10166. this._webGLVersion = 1.0;
  10167. this._badOS = false;
  10168. this._badDesktopOS = false;
  10169. /**
  10170. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10171. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10172. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10173. */
  10174. this.disableTextureBindingOptimization = false;
  10175. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10176. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10177. this.onVRRequestPresentStart = new BABYLON.Observable();
  10178. this._colorWrite = true;
  10179. this._drawCalls = new BABYLON.PerfCounter();
  10180. this._textureCollisions = new BABYLON.PerfCounter();
  10181. this._renderingQueueLaunched = false;
  10182. this._activeRenderLoops = new Array();
  10183. // Deterministic lockstepMaxSteps
  10184. this._deterministicLockstep = false;
  10185. this._lockstepMaxSteps = 4;
  10186. // Lost context
  10187. this.onContextLostObservable = new BABYLON.Observable();
  10188. this.onContextRestoredObservable = new BABYLON.Observable();
  10189. this._contextWasLost = false;
  10190. this._doNotHandleContextLost = false;
  10191. // FPS
  10192. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10193. this._fps = 60;
  10194. this._deltaTime = 0;
  10195. /**
  10196. * Turn this value on if you want to pause FPS computation when in background
  10197. */
  10198. this.disablePerformanceMonitorInBackground = false;
  10199. // States
  10200. this._depthCullingState = new BABYLON._DepthCullingState();
  10201. this._stencilState = new BABYLON._StencilState();
  10202. this._alphaState = new BABYLON._AlphaState();
  10203. this._alphaMode = Engine.ALPHA_DISABLE;
  10204. // Cache
  10205. this._internalTexturesCache = new Array();
  10206. this._activeChannel = 0;
  10207. this._currentTextureChannel = -1;
  10208. this._boundTexturesCache = {};
  10209. this._compiledEffects = {};
  10210. this._vertexAttribArraysEnabled = [];
  10211. this._uintIndicesCurrentlySet = false;
  10212. this._currentBoundBuffer = new Array();
  10213. this._currentBufferPointers = new Array();
  10214. this._currentInstanceLocations = new Array();
  10215. this._currentInstanceBuffers = new Array();
  10216. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10217. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10218. this._vaoRecordInProgress = false;
  10219. this._mustWipeVertexAttributes = false;
  10220. this._nextFreeTextureSlots = new Array();
  10221. this._maxSimultaneousTextures = 0;
  10222. this._activeRequests = new Array();
  10223. // Hardware supported Compressed Textures
  10224. this._texturesSupported = new Array();
  10225. this._onVRFullScreenTriggered = function () {
  10226. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10227. //get the old size before we change
  10228. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10229. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10230. //get the width and height, change the render size
  10231. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10232. _this.setHardwareScalingLevel(1);
  10233. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10234. }
  10235. else {
  10236. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10237. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10238. }
  10239. };
  10240. this._boundUniforms = {};
  10241. // Register promises
  10242. BABYLON.PromisePolyfill.Apply();
  10243. var canvas = null;
  10244. Engine.Instances.push(this);
  10245. if (!canvasOrContext) {
  10246. return;
  10247. }
  10248. options = options || {};
  10249. if (canvasOrContext.getContext) {
  10250. canvas = canvasOrContext;
  10251. this._renderingCanvas = canvas;
  10252. if (antialias != null) {
  10253. options.antialias = antialias;
  10254. }
  10255. if (options.deterministicLockstep === undefined) {
  10256. options.deterministicLockstep = false;
  10257. }
  10258. if (options.lockstepMaxSteps === undefined) {
  10259. options.lockstepMaxSteps = 4;
  10260. }
  10261. if (options.preserveDrawingBuffer === undefined) {
  10262. options.preserveDrawingBuffer = false;
  10263. }
  10264. if (options.audioEngine === undefined) {
  10265. options.audioEngine = true;
  10266. }
  10267. if (options.stencil === undefined) {
  10268. options.stencil = true;
  10269. }
  10270. this._deterministicLockstep = options.deterministicLockstep;
  10271. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10272. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10273. // Exceptions
  10274. if (navigator && navigator.userAgent) {
  10275. var ua = navigator.userAgent;
  10276. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10277. var exception = _a[_i];
  10278. var key = exception.key;
  10279. var targets = exception.targets;
  10280. if (ua.indexOf(key) > -1) {
  10281. if (exception.capture && exception.captureConstraint) {
  10282. var capture = exception.capture;
  10283. var constraint = exception.captureConstraint;
  10284. var regex = new RegExp(capture);
  10285. var matches = regex.exec(ua);
  10286. if (matches && matches.length > 0) {
  10287. var capturedValue = parseInt(matches[matches.length - 1]);
  10288. if (capturedValue >= constraint) {
  10289. continue;
  10290. }
  10291. }
  10292. }
  10293. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10294. var target = targets_1[_b];
  10295. switch (target) {
  10296. case "uniformBuffer":
  10297. this.disableUniformBuffers = true;
  10298. break;
  10299. case "textureBindingOptimization":
  10300. this.disableTextureBindingOptimization = true;
  10301. break;
  10302. }
  10303. }
  10304. break;
  10305. }
  10306. }
  10307. }
  10308. // GL
  10309. if (!options.disableWebGL2Support) {
  10310. try {
  10311. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10312. if (this._gl) {
  10313. this._webGLVersion = 2.0;
  10314. }
  10315. }
  10316. catch (e) {
  10317. // Do nothing
  10318. }
  10319. }
  10320. if (!this._gl) {
  10321. if (!canvas) {
  10322. throw new Error("The provided canvas is null or undefined.");
  10323. }
  10324. try {
  10325. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10326. }
  10327. catch (e) {
  10328. throw new Error("WebGL not supported");
  10329. }
  10330. }
  10331. if (!this._gl) {
  10332. throw new Error("WebGL not supported");
  10333. }
  10334. this._onCanvasFocus = function () {
  10335. _this.onCanvasFocusObservable.notifyObservers(_this);
  10336. };
  10337. this._onCanvasBlur = function () {
  10338. _this.onCanvasBlurObservable.notifyObservers(_this);
  10339. };
  10340. canvas.addEventListener("focus", this._onCanvasFocus);
  10341. canvas.addEventListener("blur", this._onCanvasBlur);
  10342. this._onBlur = function () {
  10343. if (_this.disablePerformanceMonitorInBackground) {
  10344. _this._performanceMonitor.disable();
  10345. }
  10346. _this._windowIsBackground = true;
  10347. };
  10348. this._onFocus = function () {
  10349. if (_this.disablePerformanceMonitorInBackground) {
  10350. _this._performanceMonitor.enable();
  10351. }
  10352. _this._windowIsBackground = false;
  10353. };
  10354. this._onCanvasPointerOut = function () {
  10355. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  10356. };
  10357. window.addEventListener("blur", this._onBlur);
  10358. window.addEventListener("focus", this._onFocus);
  10359. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10360. // Context lost
  10361. if (!this._doNotHandleContextLost) {
  10362. this._onContextLost = function (evt) {
  10363. evt.preventDefault();
  10364. _this._contextWasLost = true;
  10365. BABYLON.Tools.Warn("WebGL context lost.");
  10366. _this.onContextLostObservable.notifyObservers(_this);
  10367. };
  10368. this._onContextRestored = function (evt) {
  10369. // Adding a timeout to avoid race condition at browser level
  10370. setTimeout(function () {
  10371. // Rebuild gl context
  10372. _this._initGLContext();
  10373. // Rebuild effects
  10374. _this._rebuildEffects();
  10375. // Rebuild textures
  10376. _this._rebuildInternalTextures();
  10377. // Rebuild buffers
  10378. _this._rebuildBuffers();
  10379. // Cache
  10380. _this.wipeCaches(true);
  10381. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10382. _this.onContextRestoredObservable.notifyObservers(_this);
  10383. _this._contextWasLost = false;
  10384. }, 0);
  10385. };
  10386. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10387. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10388. }
  10389. }
  10390. else {
  10391. this._gl = canvasOrContext;
  10392. this._renderingCanvas = this._gl.canvas;
  10393. if (this._gl.renderbufferStorageMultisample) {
  10394. this._webGLVersion = 2.0;
  10395. }
  10396. options.stencil = this._gl.getContextAttributes().stencil;
  10397. }
  10398. // Viewport
  10399. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10400. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10401. this.resize();
  10402. this._isStencilEnable = options.stencil ? true : false;
  10403. this._initGLContext();
  10404. if (canvas) {
  10405. // Fullscreen
  10406. this._onFullscreenChange = function () {
  10407. if (document.fullscreen !== undefined) {
  10408. _this.isFullscreen = document.fullscreen;
  10409. }
  10410. else if (document.mozFullScreen !== undefined) {
  10411. _this.isFullscreen = document.mozFullScreen;
  10412. }
  10413. else if (document.webkitIsFullScreen !== undefined) {
  10414. _this.isFullscreen = document.webkitIsFullScreen;
  10415. }
  10416. else if (document.msIsFullScreen !== undefined) {
  10417. _this.isFullscreen = document.msIsFullScreen;
  10418. }
  10419. // Pointer lock
  10420. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10421. canvas.requestPointerLock = canvas.requestPointerLock ||
  10422. canvas.msRequestPointerLock ||
  10423. canvas.mozRequestPointerLock ||
  10424. canvas.webkitRequestPointerLock;
  10425. if (canvas.requestPointerLock) {
  10426. canvas.requestPointerLock();
  10427. }
  10428. }
  10429. };
  10430. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10431. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10432. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10433. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10434. // Pointer lock
  10435. this._onPointerLockChange = function () {
  10436. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10437. document.webkitPointerLockElement === canvas ||
  10438. document.msPointerLockElement === canvas ||
  10439. document.pointerLockElement === canvas);
  10440. };
  10441. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10442. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10443. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10444. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10445. this._onVRDisplayPointerRestricted = function () {
  10446. if (canvas) {
  10447. canvas.requestPointerLock();
  10448. }
  10449. };
  10450. this._onVRDisplayPointerUnrestricted = function () {
  10451. document.exitPointerLock();
  10452. };
  10453. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10454. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10455. }
  10456. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10457. Engine.audioEngine = new BABYLON.AudioEngine();
  10458. }
  10459. // Prepare buffer pointers
  10460. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10461. this._currentBufferPointers[i] = new BufferPointer();
  10462. }
  10463. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10464. // Load WebVR Devices
  10465. if (options.autoEnableWebVR) {
  10466. this.initWebVR();
  10467. }
  10468. // Detect if we are running on a faulty buggy OS.
  10469. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10470. // Detect if we are running on a faulty buggy desktop OS.
  10471. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10472. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10473. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10474. }
  10475. Object.defineProperty(Engine, "LastCreatedEngine", {
  10476. get: function () {
  10477. if (Engine.Instances.length === 0) {
  10478. return null;
  10479. }
  10480. return Engine.Instances[Engine.Instances.length - 1];
  10481. },
  10482. enumerable: true,
  10483. configurable: true
  10484. });
  10485. Object.defineProperty(Engine, "LastCreatedScene", {
  10486. get: function () {
  10487. var lastCreatedEngine = Engine.LastCreatedEngine;
  10488. if (!lastCreatedEngine) {
  10489. return null;
  10490. }
  10491. if (lastCreatedEngine.scenes.length === 0) {
  10492. return null;
  10493. }
  10494. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10495. },
  10496. enumerable: true,
  10497. configurable: true
  10498. });
  10499. /**
  10500. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10501. */
  10502. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10503. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10504. var engine = Engine.Instances[engineIndex];
  10505. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10506. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10507. }
  10508. }
  10509. };
  10510. Object.defineProperty(Engine, "NEVER", {
  10511. get: function () {
  10512. return Engine._NEVER;
  10513. },
  10514. enumerable: true,
  10515. configurable: true
  10516. });
  10517. Object.defineProperty(Engine, "ALWAYS", {
  10518. get: function () {
  10519. return Engine._ALWAYS;
  10520. },
  10521. enumerable: true,
  10522. configurable: true
  10523. });
  10524. Object.defineProperty(Engine, "LESS", {
  10525. get: function () {
  10526. return Engine._LESS;
  10527. },
  10528. enumerable: true,
  10529. configurable: true
  10530. });
  10531. Object.defineProperty(Engine, "EQUAL", {
  10532. get: function () {
  10533. return Engine._EQUAL;
  10534. },
  10535. enumerable: true,
  10536. configurable: true
  10537. });
  10538. Object.defineProperty(Engine, "LEQUAL", {
  10539. get: function () {
  10540. return Engine._LEQUAL;
  10541. },
  10542. enumerable: true,
  10543. configurable: true
  10544. });
  10545. Object.defineProperty(Engine, "GREATER", {
  10546. get: function () {
  10547. return Engine._GREATER;
  10548. },
  10549. enumerable: true,
  10550. configurable: true
  10551. });
  10552. Object.defineProperty(Engine, "GEQUAL", {
  10553. get: function () {
  10554. return Engine._GEQUAL;
  10555. },
  10556. enumerable: true,
  10557. configurable: true
  10558. });
  10559. Object.defineProperty(Engine, "NOTEQUAL", {
  10560. get: function () {
  10561. return Engine._NOTEQUAL;
  10562. },
  10563. enumerable: true,
  10564. configurable: true
  10565. });
  10566. Object.defineProperty(Engine, "KEEP", {
  10567. get: function () {
  10568. return Engine._KEEP;
  10569. },
  10570. enumerable: true,
  10571. configurable: true
  10572. });
  10573. Object.defineProperty(Engine, "REPLACE", {
  10574. get: function () {
  10575. return Engine._REPLACE;
  10576. },
  10577. enumerable: true,
  10578. configurable: true
  10579. });
  10580. Object.defineProperty(Engine, "INCR", {
  10581. get: function () {
  10582. return Engine._INCR;
  10583. },
  10584. enumerable: true,
  10585. configurable: true
  10586. });
  10587. Object.defineProperty(Engine, "DECR", {
  10588. get: function () {
  10589. return Engine._DECR;
  10590. },
  10591. enumerable: true,
  10592. configurable: true
  10593. });
  10594. Object.defineProperty(Engine, "INVERT", {
  10595. get: function () {
  10596. return Engine._INVERT;
  10597. },
  10598. enumerable: true,
  10599. configurable: true
  10600. });
  10601. Object.defineProperty(Engine, "INCR_WRAP", {
  10602. get: function () {
  10603. return Engine._INCR_WRAP;
  10604. },
  10605. enumerable: true,
  10606. configurable: true
  10607. });
  10608. Object.defineProperty(Engine, "DECR_WRAP", {
  10609. get: function () {
  10610. return Engine._DECR_WRAP;
  10611. },
  10612. enumerable: true,
  10613. configurable: true
  10614. });
  10615. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10616. get: function () {
  10617. return Engine._ALPHA_DISABLE;
  10618. },
  10619. enumerable: true,
  10620. configurable: true
  10621. });
  10622. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10623. get: function () {
  10624. return Engine._ALPHA_ONEONE;
  10625. },
  10626. enumerable: true,
  10627. configurable: true
  10628. });
  10629. Object.defineProperty(Engine, "ALPHA_ADD", {
  10630. get: function () {
  10631. return Engine._ALPHA_ADD;
  10632. },
  10633. enumerable: true,
  10634. configurable: true
  10635. });
  10636. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10637. get: function () {
  10638. return Engine._ALPHA_COMBINE;
  10639. },
  10640. enumerable: true,
  10641. configurable: true
  10642. });
  10643. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10644. get: function () {
  10645. return Engine._ALPHA_SUBTRACT;
  10646. },
  10647. enumerable: true,
  10648. configurable: true
  10649. });
  10650. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10651. get: function () {
  10652. return Engine._ALPHA_MULTIPLY;
  10653. },
  10654. enumerable: true,
  10655. configurable: true
  10656. });
  10657. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10658. get: function () {
  10659. return Engine._ALPHA_MAXIMIZED;
  10660. },
  10661. enumerable: true,
  10662. configurable: true
  10663. });
  10664. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10665. get: function () {
  10666. return Engine._ALPHA_PREMULTIPLIED;
  10667. },
  10668. enumerable: true,
  10669. configurable: true
  10670. });
  10671. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10672. get: function () {
  10673. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10674. },
  10675. enumerable: true,
  10676. configurable: true
  10677. });
  10678. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10679. get: function () {
  10680. return Engine._ALPHA_INTERPOLATE;
  10681. },
  10682. enumerable: true,
  10683. configurable: true
  10684. });
  10685. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10686. get: function () {
  10687. return Engine._ALPHA_SCREENMODE;
  10688. },
  10689. enumerable: true,
  10690. configurable: true
  10691. });
  10692. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10693. get: function () {
  10694. return Engine._DELAYLOADSTATE_NONE;
  10695. },
  10696. enumerable: true,
  10697. configurable: true
  10698. });
  10699. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10700. get: function () {
  10701. return Engine._DELAYLOADSTATE_LOADED;
  10702. },
  10703. enumerable: true,
  10704. configurable: true
  10705. });
  10706. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10707. get: function () {
  10708. return Engine._DELAYLOADSTATE_LOADING;
  10709. },
  10710. enumerable: true,
  10711. configurable: true
  10712. });
  10713. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10714. get: function () {
  10715. return Engine._DELAYLOADSTATE_NOTLOADED;
  10716. },
  10717. enumerable: true,
  10718. configurable: true
  10719. });
  10720. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10721. get: function () {
  10722. return Engine._TEXTUREFORMAT_ALPHA;
  10723. },
  10724. enumerable: true,
  10725. configurable: true
  10726. });
  10727. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10728. get: function () {
  10729. return Engine._TEXTUREFORMAT_LUMINANCE;
  10730. },
  10731. enumerable: true,
  10732. configurable: true
  10733. });
  10734. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10735. get: function () {
  10736. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10737. },
  10738. enumerable: true,
  10739. configurable: true
  10740. });
  10741. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10742. get: function () {
  10743. return Engine._TEXTUREFORMAT_RGB;
  10744. },
  10745. enumerable: true,
  10746. configurable: true
  10747. });
  10748. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10749. get: function () {
  10750. return Engine._TEXTUREFORMAT_RGBA;
  10751. },
  10752. enumerable: true,
  10753. configurable: true
  10754. });
  10755. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10756. get: function () {
  10757. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10758. },
  10759. enumerable: true,
  10760. configurable: true
  10761. });
  10762. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10763. get: function () {
  10764. return Engine._TEXTURETYPE_FLOAT;
  10765. },
  10766. enumerable: true,
  10767. configurable: true
  10768. });
  10769. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10770. get: function () {
  10771. return Engine._TEXTURETYPE_HALF_FLOAT;
  10772. },
  10773. enumerable: true,
  10774. configurable: true
  10775. });
  10776. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10777. get: function () {
  10778. return Engine._SCALEMODE_FLOOR;
  10779. },
  10780. enumerable: true,
  10781. configurable: true
  10782. });
  10783. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10784. get: function () {
  10785. return Engine._SCALEMODE_NEAREST;
  10786. },
  10787. enumerable: true,
  10788. configurable: true
  10789. });
  10790. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  10791. get: function () {
  10792. return Engine._SCALEMODE_CEILING;
  10793. },
  10794. enumerable: true,
  10795. configurable: true
  10796. });
  10797. Object.defineProperty(Engine, "Version", {
  10798. get: function () {
  10799. return "3.2.0-alpha7";
  10800. },
  10801. enumerable: true,
  10802. configurable: true
  10803. });
  10804. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  10805. get: function () {
  10806. return this._vrExclusivePointerMode;
  10807. },
  10808. enumerable: true,
  10809. configurable: true
  10810. });
  10811. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  10812. get: function () {
  10813. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  10814. },
  10815. enumerable: true,
  10816. configurable: true
  10817. });
  10818. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  10819. get: function () {
  10820. return this._webGLVersion < 2 || this.forcePOTTextures;
  10821. },
  10822. enumerable: true,
  10823. configurable: true
  10824. });
  10825. Object.defineProperty(Engine.prototype, "badOS", {
  10826. get: function () {
  10827. return this._badOS;
  10828. },
  10829. enumerable: true,
  10830. configurable: true
  10831. });
  10832. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  10833. get: function () {
  10834. return this._badDesktopOS;
  10835. },
  10836. enumerable: true,
  10837. configurable: true
  10838. });
  10839. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  10840. get: function () {
  10841. return this._performanceMonitor;
  10842. },
  10843. enumerable: true,
  10844. configurable: true
  10845. });
  10846. Object.defineProperty(Engine.prototype, "texturesSupported", {
  10847. get: function () {
  10848. return this._texturesSupported;
  10849. },
  10850. enumerable: true,
  10851. configurable: true
  10852. });
  10853. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  10854. get: function () {
  10855. return this._textureFormatInUse;
  10856. },
  10857. enumerable: true,
  10858. configurable: true
  10859. });
  10860. Object.defineProperty(Engine.prototype, "currentViewport", {
  10861. get: function () {
  10862. return this._cachedViewport;
  10863. },
  10864. enumerable: true,
  10865. configurable: true
  10866. });
  10867. Object.defineProperty(Engine.prototype, "emptyTexture", {
  10868. // Empty texture
  10869. get: function () {
  10870. if (!this._emptyTexture) {
  10871. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10872. }
  10873. return this._emptyTexture;
  10874. },
  10875. enumerable: true,
  10876. configurable: true
  10877. });
  10878. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  10879. get: function () {
  10880. if (!this._emptyTexture3D) {
  10881. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10882. }
  10883. return this._emptyTexture3D;
  10884. },
  10885. enumerable: true,
  10886. configurable: true
  10887. });
  10888. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  10889. get: function () {
  10890. if (!this._emptyCubeTexture) {
  10891. var faceData = new Uint8Array(4);
  10892. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  10893. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10894. }
  10895. return this._emptyCubeTexture;
  10896. },
  10897. enumerable: true,
  10898. configurable: true
  10899. });
  10900. Engine.prototype._rebuildInternalTextures = function () {
  10901. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  10902. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  10903. var internalTexture = currentState_1[_i];
  10904. internalTexture._rebuild();
  10905. }
  10906. };
  10907. Engine.prototype._rebuildEffects = function () {
  10908. for (var key in this._compiledEffects) {
  10909. var effect = this._compiledEffects[key];
  10910. effect._prepareEffect();
  10911. }
  10912. BABYLON.Effect.ResetCache();
  10913. };
  10914. Engine.prototype._rebuildBuffers = function () {
  10915. // Index / Vertex
  10916. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  10917. var scene = _a[_i];
  10918. scene.resetCachedMaterial();
  10919. scene._rebuildGeometries();
  10920. scene._rebuildTextures();
  10921. }
  10922. // Uniforms
  10923. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  10924. var uniformBuffer = _c[_b];
  10925. uniformBuffer._rebuild();
  10926. }
  10927. };
  10928. Engine.prototype._initGLContext = function () {
  10929. // Caps
  10930. this._caps = new EngineCapabilities();
  10931. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  10932. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  10933. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  10934. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  10935. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  10936. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  10937. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  10938. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  10939. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  10940. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  10941. // Infos
  10942. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  10943. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  10944. if (rendererInfo != null) {
  10945. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  10946. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  10947. }
  10948. if (!this._glVendor) {
  10949. this._glVendor = "Unknown vendor";
  10950. }
  10951. if (!this._glRenderer) {
  10952. this._glRenderer = "Unknown renderer";
  10953. }
  10954. // Constants
  10955. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10956. if (this._gl.RGBA16F !== 0x881A) {
  10957. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10958. }
  10959. if (this._gl.RGBA32F !== 0x8814) {
  10960. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10961. }
  10962. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  10963. this._gl.DEPTH24_STENCIL8 = 35056;
  10964. }
  10965. // Extensions
  10966. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  10967. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  10968. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10969. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10970. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  10971. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  10972. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  10973. 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');
  10974. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  10975. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  10976. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  10977. this._caps.highPrecisionShaderSupported = true;
  10978. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  10979. if (this._caps.timerQuery) {
  10980. if (this._webGLVersion === 1) {
  10981. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  10982. }
  10983. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  10984. }
  10985. // Checks if some of the format renders first to allow the use of webgl inspector.
  10986. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  10987. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  10988. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  10989. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  10990. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  10991. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  10992. if (this._webGLVersion > 1) {
  10993. this._gl.HALF_FLOAT_OES = 0x140B;
  10994. }
  10995. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  10996. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  10997. // Draw buffers
  10998. if (this._webGLVersion > 1) {
  10999. this._caps.drawBuffersExtension = true;
  11000. }
  11001. else {
  11002. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11003. if (drawBuffersExtension !== null) {
  11004. this._caps.drawBuffersExtension = true;
  11005. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11006. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11007. for (var i = 0; i < 16; i++) {
  11008. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11009. }
  11010. }
  11011. else {
  11012. this._caps.drawBuffersExtension = false;
  11013. }
  11014. }
  11015. // Depth Texture
  11016. if (this._webGLVersion > 1) {
  11017. this._caps.depthTextureExtension = true;
  11018. }
  11019. else {
  11020. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11021. if (depthTextureExtension != null) {
  11022. this._caps.depthTextureExtension = true;
  11023. }
  11024. }
  11025. // Vertex array object
  11026. if (this._webGLVersion > 1) {
  11027. this._caps.vertexArrayObject = true;
  11028. }
  11029. else {
  11030. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11031. if (vertexArrayObjectExtension != null) {
  11032. this._caps.vertexArrayObject = true;
  11033. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11034. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11035. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11036. }
  11037. else {
  11038. this._caps.vertexArrayObject = false;
  11039. }
  11040. }
  11041. // Instances count
  11042. if (this._webGLVersion > 1) {
  11043. this._caps.instancedArrays = true;
  11044. }
  11045. else {
  11046. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11047. if (instanceExtension != null) {
  11048. this._caps.instancedArrays = true;
  11049. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11050. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11051. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11052. }
  11053. else {
  11054. this._caps.instancedArrays = false;
  11055. }
  11056. }
  11057. // Intelligently add supported compressed formats in order to check for.
  11058. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11059. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11060. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11061. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11062. if (this._caps.astc)
  11063. this.texturesSupported.push('-astc.ktx');
  11064. if (this._caps.s3tc)
  11065. this.texturesSupported.push('-dxt.ktx');
  11066. if (this._caps.pvrtc)
  11067. this.texturesSupported.push('-pvrtc.ktx');
  11068. if (this._caps.etc2)
  11069. this.texturesSupported.push('-etc2.ktx');
  11070. if (this._caps.etc1)
  11071. this.texturesSupported.push('-etc1.ktx');
  11072. if (this._gl.getShaderPrecisionFormat) {
  11073. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11074. if (highp) {
  11075. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11076. }
  11077. }
  11078. // Depth buffer
  11079. this.setDepthBuffer(true);
  11080. this.setDepthFunctionToLessOrEqual();
  11081. this.setDepthWrite(true);
  11082. // Texture maps
  11083. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11084. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11085. this._nextFreeTextureSlots.push(slot);
  11086. }
  11087. };
  11088. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11089. get: function () {
  11090. return this._webGLVersion;
  11091. },
  11092. enumerable: true,
  11093. configurable: true
  11094. });
  11095. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11096. /**
  11097. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11098. */
  11099. get: function () {
  11100. return this._isStencilEnable;
  11101. },
  11102. enumerable: true,
  11103. configurable: true
  11104. });
  11105. Engine.prototype._prepareWorkingCanvas = function () {
  11106. if (this._workingCanvas) {
  11107. return;
  11108. }
  11109. this._workingCanvas = document.createElement("canvas");
  11110. var context = this._workingCanvas.getContext("2d");
  11111. if (context) {
  11112. this._workingContext = context;
  11113. }
  11114. };
  11115. Engine.prototype.resetTextureCache = function () {
  11116. for (var key in this._boundTexturesCache) {
  11117. var boundTexture = this._boundTexturesCache[key];
  11118. if (boundTexture) {
  11119. this._removeDesignatedSlot(boundTexture);
  11120. }
  11121. this._boundTexturesCache[key] = null;
  11122. }
  11123. if (!this.disableTextureBindingOptimization) {
  11124. this._nextFreeTextureSlots = [];
  11125. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11126. this._nextFreeTextureSlots.push(slot);
  11127. }
  11128. }
  11129. this._currentTextureChannel = -1;
  11130. };
  11131. Engine.prototype.isDeterministicLockStep = function () {
  11132. return this._deterministicLockstep;
  11133. };
  11134. Engine.prototype.getLockstepMaxSteps = function () {
  11135. return this._lockstepMaxSteps;
  11136. };
  11137. Engine.prototype.getGlInfo = function () {
  11138. return {
  11139. vendor: this._glVendor,
  11140. renderer: this._glRenderer,
  11141. version: this._glVersion
  11142. };
  11143. };
  11144. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11145. if (useScreen === void 0) { useScreen = false; }
  11146. var viewport = camera.viewport;
  11147. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11148. };
  11149. Engine.prototype.getRenderWidth = function (useScreen) {
  11150. if (useScreen === void 0) { useScreen = false; }
  11151. if (!useScreen && this._currentRenderTarget) {
  11152. return this._currentRenderTarget.width;
  11153. }
  11154. return this._gl.drawingBufferWidth;
  11155. };
  11156. Engine.prototype.getRenderHeight = function (useScreen) {
  11157. if (useScreen === void 0) { useScreen = false; }
  11158. if (!useScreen && this._currentRenderTarget) {
  11159. return this._currentRenderTarget.height;
  11160. }
  11161. return this._gl.drawingBufferHeight;
  11162. };
  11163. Engine.prototype.getRenderingCanvas = function () {
  11164. return this._renderingCanvas;
  11165. };
  11166. Engine.prototype.getRenderingCanvasClientRect = function () {
  11167. if (!this._renderingCanvas) {
  11168. return null;
  11169. }
  11170. return this._renderingCanvas.getBoundingClientRect();
  11171. };
  11172. Engine.prototype.setHardwareScalingLevel = function (level) {
  11173. this._hardwareScalingLevel = level;
  11174. this.resize();
  11175. };
  11176. Engine.prototype.getHardwareScalingLevel = function () {
  11177. return this._hardwareScalingLevel;
  11178. };
  11179. Engine.prototype.getLoadedTexturesCache = function () {
  11180. return this._internalTexturesCache;
  11181. };
  11182. Engine.prototype.getCaps = function () {
  11183. return this._caps;
  11184. };
  11185. Object.defineProperty(Engine.prototype, "drawCalls", {
  11186. /** The number of draw calls submitted last frame */
  11187. get: function () {
  11188. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11189. return 0;
  11190. },
  11191. enumerable: true,
  11192. configurable: true
  11193. });
  11194. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11195. get: function () {
  11196. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11197. return null;
  11198. },
  11199. enumerable: true,
  11200. configurable: true
  11201. });
  11202. Engine.prototype.getDepthFunction = function () {
  11203. return this._depthCullingState.depthFunc;
  11204. };
  11205. Engine.prototype.setDepthFunction = function (depthFunc) {
  11206. this._depthCullingState.depthFunc = depthFunc;
  11207. };
  11208. Engine.prototype.setDepthFunctionToGreater = function () {
  11209. this._depthCullingState.depthFunc = this._gl.GREATER;
  11210. };
  11211. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11212. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11213. };
  11214. Engine.prototype.setDepthFunctionToLess = function () {
  11215. this._depthCullingState.depthFunc = this._gl.LESS;
  11216. };
  11217. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11218. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11219. };
  11220. Engine.prototype.getStencilBuffer = function () {
  11221. return this._stencilState.stencilTest;
  11222. };
  11223. Engine.prototype.setStencilBuffer = function (enable) {
  11224. this._stencilState.stencilTest = enable;
  11225. };
  11226. Engine.prototype.getStencilMask = function () {
  11227. return this._stencilState.stencilMask;
  11228. };
  11229. Engine.prototype.setStencilMask = function (mask) {
  11230. this._stencilState.stencilMask = mask;
  11231. };
  11232. Engine.prototype.getStencilFunction = function () {
  11233. return this._stencilState.stencilFunc;
  11234. };
  11235. Engine.prototype.getStencilFunctionReference = function () {
  11236. return this._stencilState.stencilFuncRef;
  11237. };
  11238. Engine.prototype.getStencilFunctionMask = function () {
  11239. return this._stencilState.stencilFuncMask;
  11240. };
  11241. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11242. this._stencilState.stencilFunc = stencilFunc;
  11243. };
  11244. Engine.prototype.setStencilFunctionReference = function (reference) {
  11245. this._stencilState.stencilFuncRef = reference;
  11246. };
  11247. Engine.prototype.setStencilFunctionMask = function (mask) {
  11248. this._stencilState.stencilFuncMask = mask;
  11249. };
  11250. Engine.prototype.getStencilOperationFail = function () {
  11251. return this._stencilState.stencilOpStencilFail;
  11252. };
  11253. Engine.prototype.getStencilOperationDepthFail = function () {
  11254. return this._stencilState.stencilOpDepthFail;
  11255. };
  11256. Engine.prototype.getStencilOperationPass = function () {
  11257. return this._stencilState.stencilOpStencilDepthPass;
  11258. };
  11259. Engine.prototype.setStencilOperationFail = function (operation) {
  11260. this._stencilState.stencilOpStencilFail = operation;
  11261. };
  11262. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11263. this._stencilState.stencilOpDepthFail = operation;
  11264. };
  11265. Engine.prototype.setStencilOperationPass = function (operation) {
  11266. this._stencilState.stencilOpStencilDepthPass = operation;
  11267. };
  11268. Engine.prototype.setDitheringState = function (value) {
  11269. if (value) {
  11270. this._gl.enable(this._gl.DITHER);
  11271. }
  11272. else {
  11273. this._gl.disable(this._gl.DITHER);
  11274. }
  11275. };
  11276. Engine.prototype.setRasterizerState = function (value) {
  11277. if (value) {
  11278. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11279. }
  11280. else {
  11281. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11282. }
  11283. };
  11284. /**
  11285. * stop executing a render loop function and remove it from the execution array
  11286. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11287. */
  11288. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11289. if (!renderFunction) {
  11290. this._activeRenderLoops = [];
  11291. return;
  11292. }
  11293. var index = this._activeRenderLoops.indexOf(renderFunction);
  11294. if (index >= 0) {
  11295. this._activeRenderLoops.splice(index, 1);
  11296. }
  11297. };
  11298. Engine.prototype._renderLoop = function () {
  11299. if (!this._contextWasLost) {
  11300. var shouldRender = true;
  11301. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11302. shouldRender = false;
  11303. }
  11304. if (shouldRender) {
  11305. // Start new frame
  11306. this.beginFrame();
  11307. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11308. var renderFunction = this._activeRenderLoops[index];
  11309. renderFunction();
  11310. }
  11311. // Present
  11312. this.endFrame();
  11313. }
  11314. }
  11315. if (this._activeRenderLoops.length > 0) {
  11316. // Register new frame
  11317. var requester = null;
  11318. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11319. requester = this._vrDisplay;
  11320. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11321. }
  11322. else {
  11323. this._renderingQueueLaunched = false;
  11324. }
  11325. };
  11326. /**
  11327. * Register and execute a render loop. The engine can have more than one render function.
  11328. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11329. * @example
  11330. * engine.runRenderLoop(function () {
  11331. * scene.render()
  11332. * })
  11333. */
  11334. Engine.prototype.runRenderLoop = function (renderFunction) {
  11335. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11336. return;
  11337. }
  11338. this._activeRenderLoops.push(renderFunction);
  11339. if (!this._renderingQueueLaunched) {
  11340. this._renderingQueueLaunched = true;
  11341. this._bindedRenderFunction = this._renderLoop.bind(this);
  11342. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11343. }
  11344. };
  11345. /**
  11346. * Toggle full screen mode.
  11347. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11348. * @param {any} options - an options object to be sent to the requestFullscreen function
  11349. */
  11350. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11351. if (this.isFullscreen) {
  11352. BABYLON.Tools.ExitFullscreen();
  11353. }
  11354. else {
  11355. this._pointerLockRequested = requestPointerLock;
  11356. if (this._renderingCanvas) {
  11357. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11358. }
  11359. }
  11360. };
  11361. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11362. if (stencil === void 0) { stencil = false; }
  11363. this.applyStates();
  11364. var mode = 0;
  11365. if (backBuffer && color) {
  11366. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11367. mode |= this._gl.COLOR_BUFFER_BIT;
  11368. }
  11369. if (depth) {
  11370. this._gl.clearDepth(1.0);
  11371. mode |= this._gl.DEPTH_BUFFER_BIT;
  11372. }
  11373. if (stencil) {
  11374. this._gl.clearStencil(0);
  11375. mode |= this._gl.STENCIL_BUFFER_BIT;
  11376. }
  11377. this._gl.clear(mode);
  11378. };
  11379. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11380. var gl = this._gl;
  11381. // Save state
  11382. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11383. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11384. // Change state
  11385. gl.enable(gl.SCISSOR_TEST);
  11386. gl.scissor(x, y, width, height);
  11387. // Clear
  11388. this.clear(clearColor, true, true, true);
  11389. // Restore state
  11390. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11391. if (curScissor === true) {
  11392. gl.enable(gl.SCISSOR_TEST);
  11393. }
  11394. else {
  11395. gl.disable(gl.SCISSOR_TEST);
  11396. }
  11397. };
  11398. /**
  11399. * Set the WebGL's viewport
  11400. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11401. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11402. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11403. */
  11404. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11405. var width = requiredWidth || this.getRenderWidth();
  11406. var height = requiredHeight || this.getRenderHeight();
  11407. var x = viewport.x || 0;
  11408. var y = viewport.y || 0;
  11409. this._cachedViewport = viewport;
  11410. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11411. };
  11412. /**
  11413. * Directly set the WebGL Viewport
  11414. * The x, y, width & height are directly passed to the WebGL call
  11415. * @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.
  11416. */
  11417. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11418. var currentViewport = this._cachedViewport;
  11419. this._cachedViewport = null;
  11420. this._gl.viewport(x, y, width, height);
  11421. return currentViewport;
  11422. };
  11423. Engine.prototype.beginFrame = function () {
  11424. this.onBeginFrameObservable.notifyObservers(this);
  11425. this._measureFps();
  11426. };
  11427. Engine.prototype.endFrame = function () {
  11428. //force a flush in case we are using a bad OS.
  11429. if (this._badOS) {
  11430. this.flushFramebuffer();
  11431. }
  11432. //submit frame to the vr device, if enabled
  11433. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11434. // TODO: We should only submit the frame if we read frameData successfully.
  11435. this._vrDisplay.submitFrame();
  11436. }
  11437. this.onEndFrameObservable.notifyObservers(this);
  11438. };
  11439. /**
  11440. * resize the view according to the canvas' size.
  11441. * @example
  11442. * window.addEventListener("resize", function () {
  11443. * engine.resize();
  11444. * });
  11445. */
  11446. Engine.prototype.resize = function () {
  11447. // We're not resizing the size of the canvas while in VR mode & presenting
  11448. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11449. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11450. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11451. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11452. }
  11453. };
  11454. /**
  11455. * force a specific size of the canvas
  11456. * @param {number} width - the new canvas' width
  11457. * @param {number} height - the new canvas' height
  11458. */
  11459. Engine.prototype.setSize = function (width, height) {
  11460. if (!this._renderingCanvas) {
  11461. return;
  11462. }
  11463. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11464. return;
  11465. }
  11466. this._renderingCanvas.width = width;
  11467. this._renderingCanvas.height = height;
  11468. for (var index = 0; index < this.scenes.length; index++) {
  11469. var scene = this.scenes[index];
  11470. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11471. var cam = scene.cameras[camIndex];
  11472. cam._currentRenderId = 0;
  11473. }
  11474. }
  11475. if (this.onResizeObservable.hasObservers) {
  11476. this.onResizeObservable.notifyObservers(this);
  11477. }
  11478. };
  11479. // WebVR functions
  11480. Engine.prototype.isVRDevicePresent = function () {
  11481. return !!this._vrDisplay;
  11482. };
  11483. Engine.prototype.getVRDevice = function () {
  11484. return this._vrDisplay;
  11485. };
  11486. Engine.prototype.initWebVR = function () {
  11487. var _this = this;
  11488. var notifyObservers = function () {
  11489. var eventArgs = {
  11490. vrDisplay: _this._vrDisplay,
  11491. vrSupported: _this._vrSupported
  11492. };
  11493. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11494. };
  11495. if (!this._onVrDisplayConnect) {
  11496. this._onVrDisplayConnect = function (event) {
  11497. _this._vrDisplay = event.display;
  11498. notifyObservers();
  11499. };
  11500. this._onVrDisplayDisconnect = function () {
  11501. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11502. _this._vrDisplay = undefined;
  11503. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11504. notifyObservers();
  11505. };
  11506. this._onVrDisplayPresentChange = function () {
  11507. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11508. };
  11509. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11510. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11511. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11512. }
  11513. this._getVRDisplays(notifyObservers);
  11514. return this.onVRDisplayChangedObservable;
  11515. };
  11516. Engine.prototype.enableVR = function () {
  11517. var _this = this;
  11518. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11519. var onResolved = function () {
  11520. _this.onVRRequestPresentComplete.notifyObservers(true);
  11521. _this._onVRFullScreenTriggered();
  11522. };
  11523. var onRejected = function () {
  11524. _this.onVRRequestPresentComplete.notifyObservers(false);
  11525. };
  11526. this.onVRRequestPresentStart.notifyObservers(this);
  11527. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11528. }
  11529. };
  11530. Engine.prototype.disableVR = function () {
  11531. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11532. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11533. }
  11534. };
  11535. Engine.prototype._getVRDisplays = function (callback) {
  11536. var _this = this;
  11537. var getWebVRDevices = function (devices) {
  11538. _this._vrSupported = true;
  11539. // note that devices may actually be an empty array. This is fine;
  11540. // we expect this._vrDisplay to be undefined in this case.
  11541. return _this._vrDisplay = devices[0];
  11542. };
  11543. if (navigator.getVRDisplays) {
  11544. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  11545. // TODO: System CANNOT support WebVR, despite API presence.
  11546. _this._vrSupported = false;
  11547. callback();
  11548. });
  11549. }
  11550. else {
  11551. // TODO: Browser does not support WebVR
  11552. this._vrDisplay = undefined;
  11553. this._vrSupported = false;
  11554. callback();
  11555. }
  11556. };
  11557. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  11558. if (this._currentRenderTarget) {
  11559. this.unBindFramebuffer(this._currentRenderTarget);
  11560. }
  11561. this._currentRenderTarget = texture;
  11562. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11563. var gl = this._gl;
  11564. if (texture.isCube) {
  11565. if (faceIndex === undefined) {
  11566. faceIndex = 0;
  11567. }
  11568. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11569. }
  11570. if (this._cachedViewport && !forceFullscreenViewport) {
  11571. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11572. }
  11573. else {
  11574. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11575. }
  11576. this.wipeCaches();
  11577. };
  11578. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11579. if (this._currentFramebuffer !== framebuffer) {
  11580. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11581. this._currentFramebuffer = framebuffer;
  11582. }
  11583. };
  11584. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11585. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11586. this._currentRenderTarget = null;
  11587. // If MSAA, we need to bitblt back to main texture
  11588. var gl = this._gl;
  11589. if (texture._MSAAFramebuffer) {
  11590. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11591. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11592. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11593. }
  11594. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11595. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11596. gl.generateMipmap(gl.TEXTURE_2D);
  11597. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11598. }
  11599. if (onBeforeUnbind) {
  11600. if (texture._MSAAFramebuffer) {
  11601. // Bind the correct framebuffer
  11602. this.bindUnboundFramebuffer(texture._framebuffer);
  11603. }
  11604. onBeforeUnbind();
  11605. }
  11606. this.bindUnboundFramebuffer(null);
  11607. };
  11608. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11609. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11610. this._currentRenderTarget = null;
  11611. // If MSAA, we need to bitblt back to main texture
  11612. var gl = this._gl;
  11613. if (textures[0]._MSAAFramebuffer) {
  11614. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11615. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11616. var attachments = textures[0]._attachments;
  11617. if (!attachments) {
  11618. attachments = new Array(textures.length);
  11619. textures[0]._attachments = attachments;
  11620. }
  11621. for (var i = 0; i < textures.length; i++) {
  11622. var texture = textures[i];
  11623. for (var j = 0; j < attachments.length; j++) {
  11624. attachments[j] = gl.NONE;
  11625. }
  11626. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11627. gl.readBuffer(attachments[i]);
  11628. gl.drawBuffers(attachments);
  11629. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11630. }
  11631. for (var i = 0; i < attachments.length; i++) {
  11632. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11633. }
  11634. gl.drawBuffers(attachments);
  11635. }
  11636. for (var i = 0; i < textures.length; i++) {
  11637. var texture = textures[i];
  11638. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11639. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11640. gl.generateMipmap(gl.TEXTURE_2D);
  11641. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11642. }
  11643. }
  11644. if (onBeforeUnbind) {
  11645. if (textures[0]._MSAAFramebuffer) {
  11646. // Bind the correct framebuffer
  11647. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11648. }
  11649. onBeforeUnbind();
  11650. }
  11651. this.bindUnboundFramebuffer(null);
  11652. };
  11653. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11654. if (texture.generateMipMaps) {
  11655. var gl = this._gl;
  11656. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11657. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11658. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11659. }
  11660. };
  11661. Engine.prototype.flushFramebuffer = function () {
  11662. this._gl.flush();
  11663. };
  11664. Engine.prototype.restoreDefaultFramebuffer = function () {
  11665. if (this._currentRenderTarget) {
  11666. this.unBindFramebuffer(this._currentRenderTarget);
  11667. }
  11668. else {
  11669. this.bindUnboundFramebuffer(null);
  11670. }
  11671. if (this._cachedViewport) {
  11672. this.setViewport(this._cachedViewport);
  11673. }
  11674. this.wipeCaches();
  11675. };
  11676. // UBOs
  11677. Engine.prototype.createUniformBuffer = function (elements) {
  11678. var ubo = this._gl.createBuffer();
  11679. if (!ubo) {
  11680. throw new Error("Unable to create uniform buffer");
  11681. }
  11682. this.bindUniformBuffer(ubo);
  11683. if (elements instanceof Float32Array) {
  11684. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11685. }
  11686. else {
  11687. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11688. }
  11689. this.bindUniformBuffer(null);
  11690. ubo.references = 1;
  11691. return ubo;
  11692. };
  11693. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11694. var ubo = this._gl.createBuffer();
  11695. if (!ubo) {
  11696. throw new Error("Unable to create dynamic uniform buffer");
  11697. }
  11698. this.bindUniformBuffer(ubo);
  11699. if (elements instanceof Float32Array) {
  11700. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  11701. }
  11702. else {
  11703. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  11704. }
  11705. this.bindUniformBuffer(null);
  11706. ubo.references = 1;
  11707. return ubo;
  11708. };
  11709. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11710. this.bindUniformBuffer(uniformBuffer);
  11711. if (offset === undefined) {
  11712. offset = 0;
  11713. }
  11714. if (count === undefined) {
  11715. if (elements instanceof Float32Array) {
  11716. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11717. }
  11718. else {
  11719. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11720. }
  11721. }
  11722. else {
  11723. if (elements instanceof Float32Array) {
  11724. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11725. }
  11726. else {
  11727. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11728. }
  11729. }
  11730. this.bindUniformBuffer(null);
  11731. };
  11732. // VBOs
  11733. Engine.prototype._resetVertexBufferBinding = function () {
  11734. this.bindArrayBuffer(null);
  11735. this._cachedVertexBuffers = null;
  11736. };
  11737. Engine.prototype.createVertexBuffer = function (vertices) {
  11738. var vbo = this._gl.createBuffer();
  11739. if (!vbo) {
  11740. throw new Error("Unable to create vertex buffer");
  11741. }
  11742. this.bindArrayBuffer(vbo);
  11743. if (vertices instanceof Float32Array) {
  11744. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11745. }
  11746. else {
  11747. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11748. }
  11749. this._resetVertexBufferBinding();
  11750. vbo.references = 1;
  11751. return vbo;
  11752. };
  11753. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  11754. var vbo = this._gl.createBuffer();
  11755. if (!vbo) {
  11756. throw new Error("Unable to create dynamic vertex buffer");
  11757. }
  11758. this.bindArrayBuffer(vbo);
  11759. if (vertices instanceof Float32Array) {
  11760. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  11761. }
  11762. else {
  11763. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  11764. }
  11765. this._resetVertexBufferBinding();
  11766. vbo.references = 1;
  11767. return vbo;
  11768. };
  11769. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  11770. if (offset === void 0) { offset = 0; }
  11771. // Force cache update
  11772. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  11773. this.bindIndexBuffer(indexBuffer);
  11774. var arrayBuffer;
  11775. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  11776. arrayBuffer = indices;
  11777. }
  11778. else {
  11779. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11780. }
  11781. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  11782. this._resetIndexBufferBinding();
  11783. };
  11784. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  11785. this.bindArrayBuffer(vertexBuffer);
  11786. if (offset === undefined) {
  11787. offset = 0;
  11788. }
  11789. if (count === undefined) {
  11790. if (vertices instanceof Float32Array) {
  11791. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  11792. }
  11793. else {
  11794. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  11795. }
  11796. }
  11797. else {
  11798. if (vertices instanceof Float32Array) {
  11799. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  11800. }
  11801. else {
  11802. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  11803. }
  11804. }
  11805. this._resetVertexBufferBinding();
  11806. };
  11807. Engine.prototype._resetIndexBufferBinding = function () {
  11808. this.bindIndexBuffer(null);
  11809. this._cachedIndexBuffer = null;
  11810. };
  11811. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  11812. var vbo = this._gl.createBuffer();
  11813. if (!vbo) {
  11814. throw new Error("Unable to create index buffer");
  11815. }
  11816. this.bindIndexBuffer(vbo);
  11817. // Check for 32 bits indices
  11818. var arrayBuffer;
  11819. var need32Bits = false;
  11820. if (indices instanceof Uint16Array) {
  11821. arrayBuffer = indices;
  11822. }
  11823. else {
  11824. //check 32 bit support
  11825. if (this._caps.uintIndices) {
  11826. if (indices instanceof Uint32Array) {
  11827. arrayBuffer = indices;
  11828. need32Bits = true;
  11829. }
  11830. else {
  11831. //number[] or Int32Array, check if 32 bit is necessary
  11832. for (var index = 0; index < indices.length; index++) {
  11833. if (indices[index] > 65535) {
  11834. need32Bits = true;
  11835. break;
  11836. }
  11837. }
  11838. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11839. }
  11840. }
  11841. else {
  11842. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  11843. arrayBuffer = new Uint16Array(indices);
  11844. }
  11845. }
  11846. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  11847. this._resetIndexBufferBinding();
  11848. vbo.references = 1;
  11849. vbo.is32Bits = need32Bits;
  11850. return vbo;
  11851. };
  11852. Engine.prototype.bindArrayBuffer = function (buffer) {
  11853. if (!this._vaoRecordInProgress) {
  11854. this._unbindVertexArrayObject();
  11855. }
  11856. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  11857. };
  11858. Engine.prototype.bindUniformBuffer = function (buffer) {
  11859. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  11860. };
  11861. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  11862. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  11863. };
  11864. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  11865. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  11866. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  11867. };
  11868. ;
  11869. Engine.prototype.bindIndexBuffer = function (buffer) {
  11870. if (!this._vaoRecordInProgress) {
  11871. this._unbindVertexArrayObject();
  11872. }
  11873. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  11874. };
  11875. Engine.prototype.bindBuffer = function (buffer, target) {
  11876. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  11877. this._gl.bindBuffer(target, buffer);
  11878. this._currentBoundBuffer[target] = buffer;
  11879. }
  11880. };
  11881. Engine.prototype.updateArrayBuffer = function (data) {
  11882. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11883. };
  11884. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  11885. var pointer = this._currentBufferPointers[indx];
  11886. var changed = false;
  11887. if (!pointer.active) {
  11888. changed = true;
  11889. pointer.active = true;
  11890. pointer.index = indx;
  11891. pointer.size = size;
  11892. pointer.type = type;
  11893. pointer.normalized = normalized;
  11894. pointer.stride = stride;
  11895. pointer.offset = offset;
  11896. pointer.buffer = buffer;
  11897. }
  11898. else {
  11899. if (pointer.buffer !== buffer) {
  11900. pointer.buffer = buffer;
  11901. changed = true;
  11902. }
  11903. if (pointer.size !== size) {
  11904. pointer.size = size;
  11905. changed = true;
  11906. }
  11907. if (pointer.type !== type) {
  11908. pointer.type = type;
  11909. changed = true;
  11910. }
  11911. if (pointer.normalized !== normalized) {
  11912. pointer.normalized = normalized;
  11913. changed = true;
  11914. }
  11915. if (pointer.stride !== stride) {
  11916. pointer.stride = stride;
  11917. changed = true;
  11918. }
  11919. if (pointer.offset !== offset) {
  11920. pointer.offset = offset;
  11921. changed = true;
  11922. }
  11923. }
  11924. if (changed || this._vaoRecordInProgress) {
  11925. this.bindArrayBuffer(buffer);
  11926. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  11927. }
  11928. };
  11929. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  11930. if (indexBuffer == null) {
  11931. return;
  11932. }
  11933. if (this._cachedIndexBuffer !== indexBuffer) {
  11934. this._cachedIndexBuffer = indexBuffer;
  11935. this.bindIndexBuffer(indexBuffer);
  11936. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  11937. }
  11938. };
  11939. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  11940. var attributes = effect.getAttributesNames();
  11941. if (!this._vaoRecordInProgress) {
  11942. this._unbindVertexArrayObject();
  11943. }
  11944. this.unbindAllAttributes();
  11945. for (var index = 0; index < attributes.length; index++) {
  11946. var order = effect.getAttributeLocation(index);
  11947. if (order >= 0) {
  11948. var vertexBuffer = vertexBuffers[attributes[index]];
  11949. if (!vertexBuffer) {
  11950. continue;
  11951. }
  11952. this._gl.enableVertexAttribArray(order);
  11953. if (!this._vaoRecordInProgress) {
  11954. this._vertexAttribArraysEnabled[order] = true;
  11955. }
  11956. var buffer = vertexBuffer.getBuffer();
  11957. if (buffer) {
  11958. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  11959. if (vertexBuffer.getIsInstanced()) {
  11960. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  11961. if (!this._vaoRecordInProgress) {
  11962. this._currentInstanceLocations.push(order);
  11963. this._currentInstanceBuffers.push(buffer);
  11964. }
  11965. }
  11966. }
  11967. }
  11968. }
  11969. };
  11970. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  11971. var vao = this._gl.createVertexArray();
  11972. this._vaoRecordInProgress = true;
  11973. this._gl.bindVertexArray(vao);
  11974. this._mustWipeVertexAttributes = true;
  11975. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  11976. this.bindIndexBuffer(indexBuffer);
  11977. this._vaoRecordInProgress = false;
  11978. this._gl.bindVertexArray(null);
  11979. return vao;
  11980. };
  11981. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  11982. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  11983. this._cachedVertexArrayObject = vertexArrayObject;
  11984. this._gl.bindVertexArray(vertexArrayObject);
  11985. this._cachedVertexBuffers = null;
  11986. this._cachedIndexBuffer = null;
  11987. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  11988. this._mustWipeVertexAttributes = true;
  11989. }
  11990. };
  11991. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  11992. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  11993. this._cachedVertexBuffers = vertexBuffer;
  11994. this._cachedEffectForVertexBuffers = effect;
  11995. var attributesCount = effect.getAttributesCount();
  11996. this._unbindVertexArrayObject();
  11997. this.unbindAllAttributes();
  11998. var offset = 0;
  11999. for (var index = 0; index < attributesCount; index++) {
  12000. if (index < vertexDeclaration.length) {
  12001. var order = effect.getAttributeLocation(index);
  12002. if (order >= 0) {
  12003. this._gl.enableVertexAttribArray(order);
  12004. this._vertexAttribArraysEnabled[order] = true;
  12005. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12006. }
  12007. offset += vertexDeclaration[index] * 4;
  12008. }
  12009. }
  12010. }
  12011. this._bindIndexBufferWithCache(indexBuffer);
  12012. };
  12013. Engine.prototype._unbindVertexArrayObject = function () {
  12014. if (!this._cachedVertexArrayObject) {
  12015. return;
  12016. }
  12017. this._cachedVertexArrayObject = null;
  12018. this._gl.bindVertexArray(null);
  12019. };
  12020. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12021. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12022. this._cachedVertexBuffers = vertexBuffers;
  12023. this._cachedEffectForVertexBuffers = effect;
  12024. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12025. }
  12026. this._bindIndexBufferWithCache(indexBuffer);
  12027. };
  12028. Engine.prototype.unbindInstanceAttributes = function () {
  12029. var boundBuffer;
  12030. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12031. var instancesBuffer = this._currentInstanceBuffers[i];
  12032. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12033. boundBuffer = instancesBuffer;
  12034. this.bindArrayBuffer(instancesBuffer);
  12035. }
  12036. var offsetLocation = this._currentInstanceLocations[i];
  12037. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12038. }
  12039. this._currentInstanceBuffers.length = 0;
  12040. this._currentInstanceLocations.length = 0;
  12041. };
  12042. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12043. this._gl.deleteVertexArray(vao);
  12044. };
  12045. Engine.prototype._releaseBuffer = function (buffer) {
  12046. buffer.references--;
  12047. if (buffer.references === 0) {
  12048. this._gl.deleteBuffer(buffer);
  12049. return true;
  12050. }
  12051. return false;
  12052. };
  12053. Engine.prototype.createInstancesBuffer = function (capacity) {
  12054. var buffer = this._gl.createBuffer();
  12055. if (!buffer) {
  12056. throw new Error("Unable to create instance buffer");
  12057. }
  12058. buffer.capacity = capacity;
  12059. this.bindArrayBuffer(buffer);
  12060. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12061. return buffer;
  12062. };
  12063. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12064. this._gl.deleteBuffer(buffer);
  12065. };
  12066. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12067. this.bindArrayBuffer(instancesBuffer);
  12068. if (data) {
  12069. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12070. }
  12071. if (offsetLocations[0].index !== undefined) {
  12072. var stride = 0;
  12073. for (var i = 0; i < offsetLocations.length; i++) {
  12074. var ai = offsetLocations[i];
  12075. stride += ai.attributeSize * 4;
  12076. }
  12077. for (var i = 0; i < offsetLocations.length; i++) {
  12078. var ai = offsetLocations[i];
  12079. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12080. this._gl.enableVertexAttribArray(ai.index);
  12081. this._vertexAttribArraysEnabled[ai.index] = true;
  12082. }
  12083. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12084. this._gl.vertexAttribDivisor(ai.index, 1);
  12085. this._currentInstanceLocations.push(ai.index);
  12086. this._currentInstanceBuffers.push(instancesBuffer);
  12087. }
  12088. }
  12089. else {
  12090. for (var index = 0; index < 4; index++) {
  12091. var offsetLocation = offsetLocations[index];
  12092. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12093. this._gl.enableVertexAttribArray(offsetLocation);
  12094. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12095. }
  12096. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12097. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12098. this._currentInstanceLocations.push(offsetLocation);
  12099. this._currentInstanceBuffers.push(instancesBuffer);
  12100. }
  12101. }
  12102. };
  12103. Engine.prototype.applyStates = function () {
  12104. this._depthCullingState.apply(this._gl);
  12105. this._stencilState.apply(this._gl);
  12106. this._alphaState.apply(this._gl);
  12107. };
  12108. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12109. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12110. };
  12111. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12112. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12113. };
  12114. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12115. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12116. };
  12117. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12118. // Apply states
  12119. this.applyStates();
  12120. this._drawCalls.addCount(1, false);
  12121. // Render
  12122. var drawMode = this.DrawMode(fillMode);
  12123. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12124. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12125. if (instancesCount) {
  12126. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12127. }
  12128. else {
  12129. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12130. }
  12131. };
  12132. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12133. // Apply states
  12134. this.applyStates();
  12135. this._drawCalls.addCount(1, false);
  12136. var drawMode = this.DrawMode(fillMode);
  12137. if (instancesCount) {
  12138. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12139. }
  12140. else {
  12141. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12142. }
  12143. };
  12144. Engine.prototype.DrawMode = function (fillMode) {
  12145. switch (fillMode) {
  12146. // Triangle views
  12147. case BABYLON.Material.TriangleFillMode:
  12148. return this._gl.TRIANGLES;
  12149. case BABYLON.Material.PointFillMode:
  12150. return this._gl.POINTS;
  12151. case BABYLON.Material.WireFrameFillMode:
  12152. return this._gl.LINES;
  12153. // Draw modes
  12154. case BABYLON.Material.PointListDrawMode:
  12155. return this._gl.POINTS;
  12156. case BABYLON.Material.LineListDrawMode:
  12157. return this._gl.LINES;
  12158. case BABYLON.Material.LineLoopDrawMode:
  12159. return this._gl.LINE_LOOP;
  12160. case BABYLON.Material.LineStripDrawMode:
  12161. return this._gl.LINE_STRIP;
  12162. case BABYLON.Material.TriangleStripDrawMode:
  12163. return this._gl.TRIANGLE_STRIP;
  12164. case BABYLON.Material.TriangleFanDrawMode:
  12165. return this._gl.TRIANGLE_FAN;
  12166. default:
  12167. return this._gl.TRIANGLES;
  12168. }
  12169. };
  12170. // Shaders
  12171. Engine.prototype._releaseEffect = function (effect) {
  12172. if (this._compiledEffects[effect._key]) {
  12173. delete this._compiledEffects[effect._key];
  12174. this._deleteProgram(effect.getProgram());
  12175. }
  12176. };
  12177. Engine.prototype._deleteProgram = function (program) {
  12178. if (program) {
  12179. program.__SPECTOR_rebuildProgram = null;
  12180. if (program.transformFeedback) {
  12181. this.deleteTransformFeedback(program.transformFeedback);
  12182. program.transformFeedback = null;
  12183. }
  12184. this._gl.deleteProgram(program);
  12185. }
  12186. };
  12187. /**
  12188. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12189. * @param samplers An array of string used to represent textures
  12190. */
  12191. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12192. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12193. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12194. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12195. if (this._compiledEffects[name]) {
  12196. var compiledEffect = this._compiledEffects[name];
  12197. if (onCompiled && compiledEffect.isReady()) {
  12198. onCompiled(compiledEffect);
  12199. }
  12200. return compiledEffect;
  12201. }
  12202. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12203. effect._key = name;
  12204. this._compiledEffects[name] = effect;
  12205. return effect;
  12206. };
  12207. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12208. if (uniformsNames === void 0) { uniformsNames = []; }
  12209. if (samplers === void 0) { samplers = []; }
  12210. if (defines === void 0) { defines = ""; }
  12211. return this.createEffect({
  12212. vertex: "particles",
  12213. fragmentElement: fragmentName
  12214. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12215. };
  12216. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12217. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12218. context = context || this._gl;
  12219. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12220. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12221. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12222. };
  12223. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12224. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12225. context = context || this._gl;
  12226. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12227. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12228. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12229. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12230. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12231. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12232. return program;
  12233. };
  12234. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12235. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12236. var shaderProgram = context.createProgram();
  12237. if (!shaderProgram) {
  12238. throw new Error("Unable to create program");
  12239. }
  12240. context.attachShader(shaderProgram, vertexShader);
  12241. context.attachShader(shaderProgram, fragmentShader);
  12242. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12243. var transformFeedback = this.createTransformFeedback();
  12244. this.bindTransformFeedback(transformFeedback);
  12245. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12246. shaderProgram.transformFeedback = transformFeedback;
  12247. }
  12248. context.linkProgram(shaderProgram);
  12249. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12250. this.bindTransformFeedback(null);
  12251. }
  12252. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12253. if (!linked) {
  12254. context.validateProgram(shaderProgram);
  12255. var error = context.getProgramInfoLog(shaderProgram);
  12256. if (error) {
  12257. throw new Error(error);
  12258. }
  12259. }
  12260. context.deleteShader(vertexShader);
  12261. context.deleteShader(fragmentShader);
  12262. return shaderProgram;
  12263. };
  12264. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12265. var results = new Array();
  12266. for (var index = 0; index < uniformsNames.length; index++) {
  12267. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12268. }
  12269. return results;
  12270. };
  12271. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12272. var results = [];
  12273. for (var index = 0; index < attributesNames.length; index++) {
  12274. try {
  12275. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12276. }
  12277. catch (e) {
  12278. results.push(-1);
  12279. }
  12280. }
  12281. return results;
  12282. };
  12283. Engine.prototype.enableEffect = function (effect) {
  12284. if (!effect) {
  12285. return;
  12286. }
  12287. // Use program
  12288. this.bindSamplers(effect);
  12289. this._currentEffect = effect;
  12290. if (effect.onBind) {
  12291. effect.onBind(effect);
  12292. }
  12293. effect.onBindObservable.notifyObservers(effect);
  12294. };
  12295. Engine.prototype.setIntArray = function (uniform, array) {
  12296. if (!uniform)
  12297. return;
  12298. this._gl.uniform1iv(uniform, array);
  12299. };
  12300. Engine.prototype.setIntArray2 = function (uniform, array) {
  12301. if (!uniform || array.length % 2 !== 0)
  12302. return;
  12303. this._gl.uniform2iv(uniform, array);
  12304. };
  12305. Engine.prototype.setIntArray3 = function (uniform, array) {
  12306. if (!uniform || array.length % 3 !== 0)
  12307. return;
  12308. this._gl.uniform3iv(uniform, array);
  12309. };
  12310. Engine.prototype.setIntArray4 = function (uniform, array) {
  12311. if (!uniform || array.length % 4 !== 0)
  12312. return;
  12313. this._gl.uniform4iv(uniform, array);
  12314. };
  12315. Engine.prototype.setFloatArray = function (uniform, array) {
  12316. if (!uniform)
  12317. return;
  12318. this._gl.uniform1fv(uniform, array);
  12319. };
  12320. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12321. if (!uniform || array.length % 2 !== 0)
  12322. return;
  12323. this._gl.uniform2fv(uniform, array);
  12324. };
  12325. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12326. if (!uniform || array.length % 3 !== 0)
  12327. return;
  12328. this._gl.uniform3fv(uniform, array);
  12329. };
  12330. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12331. if (!uniform || array.length % 4 !== 0)
  12332. return;
  12333. this._gl.uniform4fv(uniform, array);
  12334. };
  12335. Engine.prototype.setArray = function (uniform, array) {
  12336. if (!uniform)
  12337. return;
  12338. this._gl.uniform1fv(uniform, array);
  12339. };
  12340. Engine.prototype.setArray2 = function (uniform, array) {
  12341. if (!uniform || array.length % 2 !== 0)
  12342. return;
  12343. this._gl.uniform2fv(uniform, array);
  12344. };
  12345. Engine.prototype.setArray3 = function (uniform, array) {
  12346. if (!uniform || array.length % 3 !== 0)
  12347. return;
  12348. this._gl.uniform3fv(uniform, array);
  12349. };
  12350. Engine.prototype.setArray4 = function (uniform, array) {
  12351. if (!uniform || array.length % 4 !== 0)
  12352. return;
  12353. this._gl.uniform4fv(uniform, array);
  12354. };
  12355. Engine.prototype.setMatrices = function (uniform, matrices) {
  12356. if (!uniform)
  12357. return;
  12358. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12359. };
  12360. Engine.prototype.setMatrix = function (uniform, matrix) {
  12361. if (!uniform)
  12362. return;
  12363. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12364. };
  12365. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12366. if (!uniform)
  12367. return;
  12368. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12369. };
  12370. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12371. if (!uniform)
  12372. return;
  12373. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12374. };
  12375. Engine.prototype.setInt = function (uniform, value) {
  12376. if (!uniform)
  12377. return;
  12378. this._gl.uniform1i(uniform, value);
  12379. };
  12380. Engine.prototype.setFloat = function (uniform, value) {
  12381. if (!uniform)
  12382. return;
  12383. this._gl.uniform1f(uniform, value);
  12384. };
  12385. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12386. if (!uniform)
  12387. return;
  12388. this._gl.uniform2f(uniform, x, y);
  12389. };
  12390. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12391. if (!uniform)
  12392. return;
  12393. this._gl.uniform3f(uniform, x, y, z);
  12394. };
  12395. Engine.prototype.setBool = function (uniform, bool) {
  12396. if (!uniform)
  12397. return;
  12398. this._gl.uniform1i(uniform, bool);
  12399. };
  12400. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12401. if (!uniform)
  12402. return;
  12403. this._gl.uniform4f(uniform, x, y, z, w);
  12404. };
  12405. Engine.prototype.setColor3 = function (uniform, color3) {
  12406. if (!uniform)
  12407. return;
  12408. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12409. };
  12410. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12411. if (!uniform)
  12412. return;
  12413. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12414. };
  12415. // States
  12416. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12417. if (zOffset === void 0) { zOffset = 0; }
  12418. if (reverseSide === void 0) { reverseSide = false; }
  12419. // Culling
  12420. if (this._depthCullingState.cull !== culling || force) {
  12421. this._depthCullingState.cull = culling;
  12422. }
  12423. // Cull face
  12424. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12425. if (this._depthCullingState.cullFace !== cullFace || force) {
  12426. this._depthCullingState.cullFace = cullFace;
  12427. }
  12428. // Z offset
  12429. this.setZOffset(zOffset);
  12430. // Front face
  12431. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12432. if (this._depthCullingState.frontFace !== frontFace || force) {
  12433. this._depthCullingState.frontFace = frontFace;
  12434. }
  12435. };
  12436. Engine.prototype.setZOffset = function (value) {
  12437. this._depthCullingState.zOffset = value;
  12438. };
  12439. Engine.prototype.getZOffset = function () {
  12440. return this._depthCullingState.zOffset;
  12441. };
  12442. Engine.prototype.setDepthBuffer = function (enable) {
  12443. this._depthCullingState.depthTest = enable;
  12444. };
  12445. Engine.prototype.getDepthWrite = function () {
  12446. return this._depthCullingState.depthMask;
  12447. };
  12448. Engine.prototype.setDepthWrite = function (enable) {
  12449. this._depthCullingState.depthMask = enable;
  12450. };
  12451. Engine.prototype.setColorWrite = function (enable) {
  12452. this._gl.colorMask(enable, enable, enable, enable);
  12453. this._colorWrite = enable;
  12454. };
  12455. Engine.prototype.getColorWrite = function () {
  12456. return this._colorWrite;
  12457. };
  12458. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12459. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12460. };
  12461. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12462. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12463. if (this._alphaMode === mode) {
  12464. return;
  12465. }
  12466. switch (mode) {
  12467. case Engine.ALPHA_DISABLE:
  12468. this._alphaState.alphaBlend = false;
  12469. break;
  12470. case Engine.ALPHA_PREMULTIPLIED:
  12471. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12472. this._alphaState.alphaBlend = true;
  12473. break;
  12474. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12475. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12476. this._alphaState.alphaBlend = true;
  12477. break;
  12478. case Engine.ALPHA_COMBINE:
  12479. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12480. this._alphaState.alphaBlend = true;
  12481. break;
  12482. case Engine.ALPHA_ONEONE:
  12483. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12484. this._alphaState.alphaBlend = true;
  12485. break;
  12486. case Engine.ALPHA_ADD:
  12487. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12488. this._alphaState.alphaBlend = true;
  12489. break;
  12490. case Engine.ALPHA_SUBTRACT:
  12491. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12492. this._alphaState.alphaBlend = true;
  12493. break;
  12494. case Engine.ALPHA_MULTIPLY:
  12495. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12496. this._alphaState.alphaBlend = true;
  12497. break;
  12498. case Engine.ALPHA_MAXIMIZED:
  12499. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12500. this._alphaState.alphaBlend = true;
  12501. break;
  12502. case Engine.ALPHA_INTERPOLATE:
  12503. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12504. this._alphaState.alphaBlend = true;
  12505. break;
  12506. case Engine.ALPHA_SCREENMODE:
  12507. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12508. this._alphaState.alphaBlend = true;
  12509. break;
  12510. }
  12511. if (!noDepthWriteChange) {
  12512. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12513. }
  12514. this._alphaMode = mode;
  12515. };
  12516. Engine.prototype.getAlphaMode = function () {
  12517. return this._alphaMode;
  12518. };
  12519. // Textures
  12520. Engine.prototype.wipeCaches = function (bruteForce) {
  12521. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12522. return;
  12523. }
  12524. this._currentEffect = null;
  12525. // 6/8/2017: deltakosh: Should not be required anymore.
  12526. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12527. if (bruteForce) {
  12528. this.resetTextureCache();
  12529. this._currentProgram = null;
  12530. this._stencilState.reset();
  12531. this._depthCullingState.reset();
  12532. this.setDepthFunctionToLessOrEqual();
  12533. this._alphaState.reset();
  12534. }
  12535. this._resetVertexBufferBinding();
  12536. this._cachedIndexBuffer = null;
  12537. this._cachedEffectForVertexBuffers = null;
  12538. this._unbindVertexArrayObject();
  12539. this.bindIndexBuffer(null);
  12540. };
  12541. /**
  12542. * Set the compressed texture format to use, based on the formats you have, and the formats
  12543. * supported by the hardware / browser.
  12544. *
  12545. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12546. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12547. * to API arguments needed to compressed textures. This puts the burden on the container
  12548. * generator to house the arcane code for determining these for current & future formats.
  12549. *
  12550. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12551. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12552. *
  12553. * Note: The result of this call is not taken into account when a texture is base64.
  12554. *
  12555. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12556. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12557. *
  12558. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12559. * @returns The extension selected.
  12560. */
  12561. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12562. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12563. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12564. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12565. return this._textureFormatInUse = this._texturesSupported[i];
  12566. }
  12567. }
  12568. }
  12569. // actively set format to nothing, to allow this to be called more than once
  12570. // and possibly fail the 2nd time
  12571. this._textureFormatInUse = null;
  12572. return null;
  12573. };
  12574. Engine.prototype._createTexture = function () {
  12575. var texture = this._gl.createTexture();
  12576. if (!texture) {
  12577. throw new Error("Unable to create texture");
  12578. }
  12579. return texture;
  12580. };
  12581. /**
  12582. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12583. * @param {string} urlArg- This contains one of the following:
  12584. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12585. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12586. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12587. *
  12588. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12589. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12590. * @param {Scene} scene- Needed for loading to the correct scene.
  12591. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12592. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12593. * @param {callback} onError- Optional callback to be called upon failure.
  12594. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12595. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12596. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12597. *
  12598. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12599. */
  12600. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12601. var _this = this;
  12602. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12603. if (onLoad === void 0) { onLoad = null; }
  12604. if (onError === void 0) { onError = null; }
  12605. if (buffer === void 0) { buffer = null; }
  12606. if (fallBack === void 0) { fallBack = null; }
  12607. if (format === void 0) { format = null; }
  12608. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12609. var fromData = url.substr(0, 5) === "data:";
  12610. var fromBlob = url.substr(0, 5) === "blob:";
  12611. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12612. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12613. // establish the file extension, if possible
  12614. var lastDot = url.lastIndexOf('.');
  12615. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12616. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12617. var isTGA = (extension.indexOf(".tga") === 0);
  12618. // determine if a ktx file should be substituted
  12619. var isKTX = false;
  12620. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12621. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12622. isKTX = true;
  12623. }
  12624. if (scene) {
  12625. scene._addPendingData(texture);
  12626. }
  12627. texture.url = url;
  12628. texture.generateMipMaps = !noMipmap;
  12629. texture.samplingMode = samplingMode;
  12630. texture.invertY = invertY;
  12631. if (!this._doNotHandleContextLost) {
  12632. // Keep a link to the buffer only if we plan to handle context lost
  12633. texture._buffer = buffer;
  12634. }
  12635. var onLoadObserver = null;
  12636. if (onLoad && !fallBack) {
  12637. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12638. }
  12639. if (!fallBack)
  12640. this._internalTexturesCache.push(texture);
  12641. var onerror = function (message, exception) {
  12642. if (scene) {
  12643. scene._removePendingData(texture);
  12644. }
  12645. if (onLoadObserver) {
  12646. texture.onLoadedObservable.remove(onLoadObserver);
  12647. }
  12648. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12649. if (isKTX) {
  12650. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12651. }
  12652. else if (BABYLON.Tools.UseFallbackTexture) {
  12653. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12654. }
  12655. if (onError) {
  12656. onError(message || "Unknown error", exception);
  12657. }
  12658. };
  12659. var callback = null;
  12660. // processing for non-image formats
  12661. if (isKTX || isTGA || isDDS) {
  12662. if (isKTX) {
  12663. callback = function (data) {
  12664. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12665. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  12666. ktx.uploadLevels(_this._gl, !noMipmap);
  12667. return false;
  12668. }, samplingMode);
  12669. };
  12670. }
  12671. else if (isTGA) {
  12672. callback = function (arrayBuffer) {
  12673. var data = new Uint8Array(arrayBuffer);
  12674. var header = BABYLON.TGATools.GetTGAHeader(data);
  12675. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  12676. BABYLON.TGATools.UploadContent(_this._gl, data);
  12677. return false;
  12678. }, samplingMode);
  12679. };
  12680. }
  12681. else if (isDDS) {
  12682. callback = function (data) {
  12683. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12684. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  12685. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  12686. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  12687. return false;
  12688. }, samplingMode);
  12689. };
  12690. }
  12691. if (!buffer) {
  12692. this._loadFile(url, function (data) {
  12693. if (callback) {
  12694. callback(data);
  12695. }
  12696. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  12697. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  12698. });
  12699. }
  12700. else {
  12701. if (callback) {
  12702. callback(buffer);
  12703. }
  12704. }
  12705. // image format processing
  12706. }
  12707. else {
  12708. var onload = function (img) {
  12709. if (fromBlob && !_this._doNotHandleContextLost) {
  12710. // We need to store the image if we need to rebuild the texture
  12711. // in case of a webgl context lost
  12712. texture._buffer = img;
  12713. }
  12714. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  12715. var gl = _this._gl;
  12716. var isPot = (img.width === potWidth && img.height === potHeight);
  12717. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  12718. if (isPot) {
  12719. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12720. return false;
  12721. }
  12722. // Using shaders to rescale because canvas.drawImage is lossy
  12723. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12724. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12725. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12726. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12727. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12728. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12729. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12730. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12731. _this._releaseTexture(source);
  12732. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12733. continuationCallback();
  12734. });
  12735. return true;
  12736. }, samplingMode);
  12737. };
  12738. if (!fromData || isBase64)
  12739. if (buffer instanceof HTMLImageElement) {
  12740. onload(buffer);
  12741. }
  12742. else {
  12743. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  12744. }
  12745. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  12746. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  12747. else
  12748. onload(buffer);
  12749. }
  12750. return texture;
  12751. };
  12752. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  12753. var _this = this;
  12754. var rtt = this.createRenderTargetTexture({
  12755. width: destination.width,
  12756. height: destination.height,
  12757. }, {
  12758. generateMipMaps: false,
  12759. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  12760. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  12761. generateDepthBuffer: false,
  12762. generateStencilBuffer: false
  12763. });
  12764. if (!this._rescalePostProcess) {
  12765. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  12766. }
  12767. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  12768. _this._rescalePostProcess.onApply = function (effect) {
  12769. effect._bindTexture("textureSampler", source);
  12770. };
  12771. var hostingScene = scene;
  12772. if (!hostingScene) {
  12773. hostingScene = _this.scenes[_this.scenes.length - 1];
  12774. }
  12775. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  12776. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  12777. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  12778. _this.unBindFramebuffer(rtt);
  12779. _this._releaseTexture(rtt);
  12780. if (onComplete) {
  12781. onComplete();
  12782. }
  12783. });
  12784. };
  12785. Engine.prototype._getInternalFormat = function (format) {
  12786. var internalFormat = this._gl.RGBA;
  12787. switch (format) {
  12788. case Engine.TEXTUREFORMAT_ALPHA:
  12789. internalFormat = this._gl.ALPHA;
  12790. break;
  12791. case Engine.TEXTUREFORMAT_LUMINANCE:
  12792. internalFormat = this._gl.LUMINANCE;
  12793. break;
  12794. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  12795. internalFormat = this._gl.LUMINANCE_ALPHA;
  12796. break;
  12797. case Engine.TEXTUREFORMAT_RGB:
  12798. internalFormat = this._gl.RGB;
  12799. break;
  12800. case Engine.TEXTUREFORMAT_RGBA:
  12801. internalFormat = this._gl.RGBA;
  12802. break;
  12803. }
  12804. return internalFormat;
  12805. };
  12806. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  12807. if (compression === void 0) { compression = null; }
  12808. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12809. if (!texture) {
  12810. return;
  12811. }
  12812. var internalFormat = this._getInternalFormat(format);
  12813. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12814. var textureType = this._getWebGLTextureType(type);
  12815. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12816. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12817. if (!this._doNotHandleContextLost) {
  12818. texture._bufferView = data;
  12819. texture.format = format;
  12820. texture.type = type;
  12821. texture.invertY = invertY;
  12822. texture._compression = compression;
  12823. }
  12824. if (texture.width % 4 !== 0) {
  12825. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12826. }
  12827. if (compression && data) {
  12828. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  12829. }
  12830. else {
  12831. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  12832. }
  12833. if (texture.generateMipMaps) {
  12834. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12835. }
  12836. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12837. // this.resetTextureCache();
  12838. texture.isReady = true;
  12839. };
  12840. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  12841. if (compression === void 0) { compression = null; }
  12842. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12843. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  12844. texture.baseWidth = width;
  12845. texture.baseHeight = height;
  12846. texture.width = width;
  12847. texture.height = height;
  12848. texture.format = format;
  12849. texture.generateMipMaps = generateMipMaps;
  12850. texture.samplingMode = samplingMode;
  12851. texture.invertY = invertY;
  12852. texture._compression = compression;
  12853. texture.type = type;
  12854. if (!this._doNotHandleContextLost) {
  12855. texture._bufferView = data;
  12856. }
  12857. this.updateRawTexture(texture, data, format, invertY, compression, type);
  12858. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12859. // Filters
  12860. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12861. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12862. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12863. if (generateMipMaps) {
  12864. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12865. }
  12866. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12867. this._internalTexturesCache.push(texture);
  12868. return texture;
  12869. };
  12870. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  12871. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  12872. texture.baseWidth = width;
  12873. texture.baseHeight = height;
  12874. if (generateMipMaps) {
  12875. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  12876. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  12877. }
  12878. // this.resetTextureCache();
  12879. texture.width = width;
  12880. texture.height = height;
  12881. texture.isReady = false;
  12882. texture.generateMipMaps = generateMipMaps;
  12883. texture.samplingMode = samplingMode;
  12884. this.updateTextureSamplingMode(samplingMode, texture);
  12885. this._internalTexturesCache.push(texture);
  12886. return texture;
  12887. };
  12888. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  12889. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  12890. if (texture.isCube) {
  12891. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12892. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12893. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12894. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12895. }
  12896. else if (texture.is3D) {
  12897. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12898. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12899. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12900. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12901. }
  12902. else {
  12903. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12904. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12905. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12906. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12907. }
  12908. texture.samplingMode = samplingMode;
  12909. };
  12910. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  12911. if (premulAlpha === void 0) { premulAlpha = false; }
  12912. if (!texture) {
  12913. return;
  12914. }
  12915. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12916. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  12917. if (premulAlpha) {
  12918. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  12919. }
  12920. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  12921. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  12922. if (texture.generateMipMaps) {
  12923. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12924. }
  12925. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12926. if (premulAlpha) {
  12927. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  12928. }
  12929. texture.isReady = true;
  12930. };
  12931. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  12932. if (!texture || texture._isDisabled) {
  12933. return;
  12934. }
  12935. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12936. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  12937. try {
  12938. // Testing video texture support
  12939. if (this._videoTextureSupported === undefined) {
  12940. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  12941. if (this._gl.getError() !== 0) {
  12942. this._videoTextureSupported = false;
  12943. }
  12944. else {
  12945. this._videoTextureSupported = true;
  12946. }
  12947. }
  12948. // Copy video through the current working canvas if video texture is not supported
  12949. if (!this._videoTextureSupported) {
  12950. if (!texture._workingCanvas) {
  12951. texture._workingCanvas = document.createElement("canvas");
  12952. var context = texture._workingCanvas.getContext("2d");
  12953. if (!context) {
  12954. throw new Error("Unable to get 2d context");
  12955. }
  12956. texture._workingContext = context;
  12957. texture._workingCanvas.width = texture.width;
  12958. texture._workingCanvas.height = texture.height;
  12959. }
  12960. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  12961. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  12962. }
  12963. else {
  12964. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  12965. }
  12966. if (texture.generateMipMaps) {
  12967. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12968. }
  12969. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12970. // this.resetTextureCache();
  12971. texture.isReady = true;
  12972. }
  12973. catch (ex) {
  12974. // Something unexpected
  12975. // Let's disable the texture
  12976. texture._isDisabled = true;
  12977. }
  12978. };
  12979. Engine.prototype.createRenderTargetTexture = function (size, options) {
  12980. var fullOptions = new RenderTargetCreationOptions();
  12981. if (options !== undefined && typeof options === "object") {
  12982. fullOptions.generateMipMaps = options.generateMipMaps;
  12983. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12984. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  12985. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  12986. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  12987. }
  12988. else {
  12989. fullOptions.generateMipMaps = options;
  12990. fullOptions.generateDepthBuffer = true;
  12991. fullOptions.generateStencilBuffer = false;
  12992. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12993. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12994. }
  12995. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  12996. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  12997. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12998. }
  12999. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13000. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13001. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13002. }
  13003. var gl = this._gl;
  13004. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13005. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13006. var width = size.width || size;
  13007. var height = size.height || size;
  13008. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13009. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13010. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13011. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13012. }
  13013. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13014. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13015. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13016. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13017. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13018. // Create the framebuffer
  13019. var framebuffer = gl.createFramebuffer();
  13020. this.bindUnboundFramebuffer(framebuffer);
  13021. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13022. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13023. if (fullOptions.generateMipMaps) {
  13024. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13025. }
  13026. // Unbind
  13027. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13028. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13029. this.bindUnboundFramebuffer(null);
  13030. texture._framebuffer = framebuffer;
  13031. texture.baseWidth = width;
  13032. texture.baseHeight = height;
  13033. texture.width = width;
  13034. texture.height = height;
  13035. texture.isReady = true;
  13036. texture.samples = 1;
  13037. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13038. texture.samplingMode = fullOptions.samplingMode;
  13039. texture.type = fullOptions.type;
  13040. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13041. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13042. // this.resetTextureCache();
  13043. this._internalTexturesCache.push(texture);
  13044. return texture;
  13045. };
  13046. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13047. var generateMipMaps = false;
  13048. var generateDepthBuffer = true;
  13049. var generateStencilBuffer = false;
  13050. var generateDepthTexture = false;
  13051. var textureCount = 1;
  13052. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13053. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13054. var types = [], samplingModes = [];
  13055. if (options !== undefined) {
  13056. generateMipMaps = options.generateMipMaps;
  13057. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13058. generateStencilBuffer = options.generateStencilBuffer;
  13059. generateDepthTexture = options.generateDepthTexture;
  13060. textureCount = options.textureCount || 1;
  13061. if (options.types) {
  13062. types = options.types;
  13063. }
  13064. if (options.samplingModes) {
  13065. samplingModes = options.samplingModes;
  13066. }
  13067. }
  13068. var gl = this._gl;
  13069. // Create the framebuffer
  13070. var framebuffer = gl.createFramebuffer();
  13071. this.bindUnboundFramebuffer(framebuffer);
  13072. var width = size.width || size;
  13073. var height = size.height || size;
  13074. var textures = [];
  13075. var attachments = [];
  13076. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13077. for (var i = 0; i < textureCount; i++) {
  13078. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13079. var type = types[i] || defaultType;
  13080. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13081. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13082. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13083. }
  13084. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13085. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13086. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13087. }
  13088. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13089. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13090. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13091. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13092. }
  13093. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13094. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13095. textures.push(texture);
  13096. attachments.push(attachment);
  13097. gl.activeTexture(gl["TEXTURE" + i]);
  13098. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13099. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13100. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13101. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13102. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13103. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13104. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13105. if (generateMipMaps) {
  13106. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13107. }
  13108. // Unbind
  13109. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13110. texture._framebuffer = framebuffer;
  13111. texture._depthStencilBuffer = depthStencilBuffer;
  13112. texture.baseWidth = width;
  13113. texture.baseHeight = height;
  13114. texture.width = width;
  13115. texture.height = height;
  13116. texture.isReady = true;
  13117. texture.samples = 1;
  13118. texture.generateMipMaps = generateMipMaps;
  13119. texture.samplingMode = samplingMode;
  13120. texture.type = type;
  13121. texture._generateDepthBuffer = generateDepthBuffer;
  13122. texture._generateStencilBuffer = generateStencilBuffer;
  13123. texture._attachments = attachments;
  13124. this._internalTexturesCache.push(texture);
  13125. }
  13126. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13127. // Depth texture
  13128. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13129. gl.activeTexture(gl.TEXTURE0);
  13130. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13131. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13132. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13133. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13134. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13135. 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);
  13136. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13137. depthTexture._framebuffer = framebuffer;
  13138. depthTexture.baseWidth = width;
  13139. depthTexture.baseHeight = height;
  13140. depthTexture.width = width;
  13141. depthTexture.height = height;
  13142. depthTexture.isReady = true;
  13143. depthTexture.samples = 1;
  13144. depthTexture.generateMipMaps = generateMipMaps;
  13145. depthTexture.samplingMode = gl.NEAREST;
  13146. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13147. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13148. textures.push(depthTexture);
  13149. this._internalTexturesCache.push(depthTexture);
  13150. }
  13151. gl.drawBuffers(attachments);
  13152. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13153. this.bindUnboundFramebuffer(null);
  13154. this.resetTextureCache();
  13155. return textures;
  13156. };
  13157. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13158. if (samples === void 0) { samples = 1; }
  13159. var depthStencilBuffer = null;
  13160. var gl = this._gl;
  13161. // Create the depth/stencil buffer
  13162. if (generateStencilBuffer) {
  13163. depthStencilBuffer = gl.createRenderbuffer();
  13164. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13165. if (samples > 1) {
  13166. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13167. }
  13168. else {
  13169. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13170. }
  13171. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13172. }
  13173. else if (generateDepthBuffer) {
  13174. depthStencilBuffer = gl.createRenderbuffer();
  13175. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13176. if (samples > 1) {
  13177. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13178. }
  13179. else {
  13180. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13181. }
  13182. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13183. }
  13184. return depthStencilBuffer;
  13185. };
  13186. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13187. if (this.webGLVersion < 2 || !texture) {
  13188. return 1;
  13189. }
  13190. if (texture.samples === samples) {
  13191. return samples;
  13192. }
  13193. var gl = this._gl;
  13194. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13195. // Dispose previous render buffers
  13196. if (texture._depthStencilBuffer) {
  13197. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13198. texture._depthStencilBuffer = null;
  13199. }
  13200. if (texture._MSAAFramebuffer) {
  13201. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13202. texture._MSAAFramebuffer = null;
  13203. }
  13204. if (texture._MSAARenderBuffer) {
  13205. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13206. texture._MSAARenderBuffer = null;
  13207. }
  13208. if (samples > 1) {
  13209. var framebuffer = gl.createFramebuffer();
  13210. if (!framebuffer) {
  13211. throw new Error("Unable to create multi sampled framebuffer");
  13212. }
  13213. texture._MSAAFramebuffer = framebuffer;
  13214. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13215. var colorRenderbuffer = gl.createRenderbuffer();
  13216. if (!colorRenderbuffer) {
  13217. throw new Error("Unable to create multi sampled framebuffer");
  13218. }
  13219. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13220. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13221. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13222. texture._MSAARenderBuffer = colorRenderbuffer;
  13223. }
  13224. else {
  13225. this.bindUnboundFramebuffer(texture._framebuffer);
  13226. }
  13227. texture.samples = samples;
  13228. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13229. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13230. this.bindUnboundFramebuffer(null);
  13231. return samples;
  13232. };
  13233. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13234. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13235. return 1;
  13236. }
  13237. if (textures[0].samples === samples) {
  13238. return samples;
  13239. }
  13240. var gl = this._gl;
  13241. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13242. // Dispose previous render buffers
  13243. if (textures[0]._depthStencilBuffer) {
  13244. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13245. textures[0]._depthStencilBuffer = null;
  13246. }
  13247. if (textures[0]._MSAAFramebuffer) {
  13248. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13249. textures[0]._MSAAFramebuffer = null;
  13250. }
  13251. for (var i = 0; i < textures.length; i++) {
  13252. if (textures[i]._MSAARenderBuffer) {
  13253. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13254. textures[i]._MSAARenderBuffer = null;
  13255. }
  13256. }
  13257. if (samples > 1) {
  13258. var framebuffer = gl.createFramebuffer();
  13259. if (!framebuffer) {
  13260. throw new Error("Unable to create multi sampled framebuffer");
  13261. }
  13262. this.bindUnboundFramebuffer(framebuffer);
  13263. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13264. var attachments = [];
  13265. for (var i = 0; i < textures.length; i++) {
  13266. var texture = textures[i];
  13267. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13268. var colorRenderbuffer = gl.createRenderbuffer();
  13269. if (!colorRenderbuffer) {
  13270. throw new Error("Unable to create multi sampled framebuffer");
  13271. }
  13272. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13273. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13274. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13275. texture._MSAAFramebuffer = framebuffer;
  13276. texture._MSAARenderBuffer = colorRenderbuffer;
  13277. texture.samples = samples;
  13278. texture._depthStencilBuffer = depthStencilBuffer;
  13279. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13280. attachments.push(attachment);
  13281. }
  13282. gl.drawBuffers(attachments);
  13283. }
  13284. else {
  13285. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13286. }
  13287. this.bindUnboundFramebuffer(null);
  13288. return samples;
  13289. };
  13290. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13291. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13292. };
  13293. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13294. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13295. };
  13296. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13297. var gl = this._gl;
  13298. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13299. var generateMipMaps = true;
  13300. var generateDepthBuffer = true;
  13301. var generateStencilBuffer = false;
  13302. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13303. if (options !== undefined) {
  13304. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  13305. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13306. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  13307. if (options.samplingMode !== undefined) {
  13308. samplingMode = options.samplingMode;
  13309. }
  13310. }
  13311. texture.isCube = true;
  13312. texture.generateMipMaps = generateMipMaps;
  13313. texture.samples = 1;
  13314. texture.samplingMode = samplingMode;
  13315. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13316. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13317. for (var face = 0; face < 6; face++) {
  13318. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  13319. }
  13320. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13321. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13322. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13323. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13324. // Create the framebuffer
  13325. var framebuffer = gl.createFramebuffer();
  13326. this.bindUnboundFramebuffer(framebuffer);
  13327. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  13328. // Mipmaps
  13329. if (texture.generateMipMaps) {
  13330. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13331. }
  13332. // Unbind
  13333. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13334. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13335. this.bindUnboundFramebuffer(null);
  13336. texture._framebuffer = framebuffer;
  13337. texture.width = size;
  13338. texture.height = size;
  13339. texture.isReady = true;
  13340. //this.resetTextureCache();
  13341. this._internalTexturesCache.push(texture);
  13342. return texture;
  13343. };
  13344. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13345. var _this = this;
  13346. if (onLoad === void 0) { onLoad = null; }
  13347. if (onError === void 0) { onError = null; }
  13348. if (forcedExtension === void 0) { forcedExtension = null; }
  13349. var callback = function (loadData) {
  13350. if (!loadData) {
  13351. if (onLoad) {
  13352. onLoad(null);
  13353. }
  13354. return;
  13355. }
  13356. var texture = loadData.texture;
  13357. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13358. texture._lodGenerationScale = scale;
  13359. texture._lodGenerationOffset = offset;
  13360. if (_this._caps.textureLOD) {
  13361. // Do not add extra process if texture lod is supported.
  13362. if (onLoad) {
  13363. onLoad(texture);
  13364. }
  13365. return;
  13366. }
  13367. var mipSlices = 3;
  13368. var gl = _this._gl;
  13369. var width = loadData.width;
  13370. if (!width) {
  13371. return;
  13372. }
  13373. var textures = [];
  13374. for (var i = 0; i < mipSlices; i++) {
  13375. //compute LOD from even spacing in smoothness (matching shader calculation)
  13376. var smoothness = i / (mipSlices - 1);
  13377. var roughness = 1 - smoothness;
  13378. var minLODIndex = offset; // roughness = 0
  13379. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13380. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13381. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13382. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13383. glTextureFromLod.isCube = true;
  13384. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13385. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13386. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13387. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13388. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13389. if (loadData.isDDS) {
  13390. var info = loadData.info;
  13391. var data = loadData.data;
  13392. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13393. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13394. }
  13395. else {
  13396. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13397. }
  13398. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13399. // Wrap in a base texture for easy binding.
  13400. var lodTexture = new BABYLON.BaseTexture(scene);
  13401. lodTexture.isCube = true;
  13402. lodTexture._texture = glTextureFromLod;
  13403. glTextureFromLod.isReady = true;
  13404. textures.push(lodTexture);
  13405. }
  13406. texture._lodTextureHigh = textures[2];
  13407. texture._lodTextureMid = textures[1];
  13408. texture._lodTextureLow = textures[0];
  13409. if (onLoad) {
  13410. onLoad(texture);
  13411. }
  13412. };
  13413. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13414. };
  13415. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13416. var _this = this;
  13417. if (onLoad === void 0) { onLoad = null; }
  13418. if (onError === void 0) { onError = null; }
  13419. if (forcedExtension === void 0) { forcedExtension = null; }
  13420. var gl = this._gl;
  13421. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13422. texture.isCube = true;
  13423. texture.url = rootUrl;
  13424. texture.generateMipMaps = !noMipmap;
  13425. if (!this._doNotHandleContextLost) {
  13426. texture._extension = forcedExtension;
  13427. texture._files = files;
  13428. }
  13429. var isKTX = false;
  13430. var isDDS = false;
  13431. var lastDot = rootUrl.lastIndexOf('.');
  13432. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13433. if (this._textureFormatInUse) {
  13434. extension = this._textureFormatInUse;
  13435. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13436. isKTX = true;
  13437. }
  13438. else {
  13439. isDDS = (extension === ".dds");
  13440. }
  13441. var onerror = function (request, exception) {
  13442. if (onError && request) {
  13443. onError(request.status + " " + request.statusText, exception);
  13444. }
  13445. };
  13446. if (isKTX) {
  13447. this._loadFile(rootUrl, function (data) {
  13448. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13449. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13450. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13451. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13452. ktx.uploadLevels(_this._gl, !noMipmap);
  13453. _this.setCubeMapTextureParams(gl, loadMipmap);
  13454. texture.width = ktx.pixelWidth;
  13455. texture.height = ktx.pixelHeight;
  13456. texture.isReady = true;
  13457. }, undefined, undefined, true, onerror);
  13458. }
  13459. else if (isDDS) {
  13460. if (files && files.length === 6) {
  13461. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  13462. var info;
  13463. var loadMipmap = false;
  13464. var width = 0;
  13465. for (var index = 0; index < imgs.length; index++) {
  13466. var data = imgs[index];
  13467. info = BABYLON.DDSTools.GetDDSInfo(data);
  13468. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13469. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13470. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13471. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13472. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13473. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13474. }
  13475. texture.width = info.width;
  13476. texture.height = info.height;
  13477. texture.type = info.textureType;
  13478. width = info.width;
  13479. }
  13480. _this.setCubeMapTextureParams(gl, loadMipmap);
  13481. texture.isReady = true;
  13482. if (onLoad) {
  13483. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13484. }
  13485. }, files, onError);
  13486. }
  13487. else {
  13488. this._loadFile(rootUrl, function (data) {
  13489. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13490. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13491. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13492. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13493. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  13494. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13495. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13496. }
  13497. _this.setCubeMapTextureParams(gl, loadMipmap);
  13498. texture.width = info.width;
  13499. texture.height = info.height;
  13500. texture.isReady = true;
  13501. texture.type = info.textureType;
  13502. if (onLoad) {
  13503. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  13504. }
  13505. }, undefined, undefined, true, onerror);
  13506. }
  13507. }
  13508. else {
  13509. if (!files) {
  13510. throw new Error("Cannot load cubemap because files were not defined");
  13511. }
  13512. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  13513. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  13514. var height = width;
  13515. _this._prepareWorkingCanvas();
  13516. if (!_this._workingCanvas || !_this._workingContext) {
  13517. return;
  13518. }
  13519. _this._workingCanvas.width = width;
  13520. _this._workingCanvas.height = height;
  13521. var faces = [
  13522. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  13523. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  13524. ];
  13525. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13526. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13527. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  13528. for (var index = 0; index < faces.length; index++) {
  13529. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  13530. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  13531. }
  13532. if (!noMipmap) {
  13533. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13534. }
  13535. _this.setCubeMapTextureParams(gl, !noMipmap);
  13536. texture.width = width;
  13537. texture.height = height;
  13538. texture.isReady = true;
  13539. if (format) {
  13540. texture.format = format;
  13541. }
  13542. texture.onLoadedObservable.notifyObservers(texture);
  13543. texture.onLoadedObservable.clear();
  13544. if (onLoad) {
  13545. onLoad();
  13546. }
  13547. }, files, onError);
  13548. }
  13549. this._internalTexturesCache.push(texture);
  13550. return texture;
  13551. };
  13552. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  13553. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13554. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  13555. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13556. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13557. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13558. // this.resetTextureCache();
  13559. };
  13560. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  13561. if (compression === void 0) { compression = null; }
  13562. if (level === void 0) { level = 0; }
  13563. texture._bufferViewArray = data;
  13564. texture.format = format;
  13565. texture.type = type;
  13566. texture.invertY = invertY;
  13567. texture._compression = compression;
  13568. var gl = this._gl;
  13569. var textureType = this._getWebGLTextureType(type);
  13570. var internalFormat = this._getInternalFormat(format);
  13571. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  13572. var needConversion = false;
  13573. if (internalFormat === gl.RGB) {
  13574. internalFormat = gl.RGBA;
  13575. needConversion = true;
  13576. }
  13577. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13578. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13579. if (texture.width % 4 !== 0) {
  13580. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  13581. }
  13582. // Data are known to be in +X +Y +Z -X -Y -Z
  13583. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13584. var faceData = data[faceIndex];
  13585. if (compression) {
  13586. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  13587. }
  13588. else {
  13589. if (needConversion) {
  13590. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  13591. }
  13592. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  13593. }
  13594. }
  13595. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13596. if (isPot && texture.generateMipMaps && level === 0) {
  13597. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13598. }
  13599. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13600. // this.resetTextureCache();
  13601. texture.isReady = true;
  13602. };
  13603. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  13604. if (compression === void 0) { compression = null; }
  13605. var gl = this._gl;
  13606. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  13607. texture.isCube = true;
  13608. texture.generateMipMaps = generateMipMaps;
  13609. texture.format = format;
  13610. texture.type = type;
  13611. if (!this._doNotHandleContextLost) {
  13612. texture._bufferViewArray = data;
  13613. }
  13614. var textureType = this._getWebGLTextureType(type);
  13615. var internalFormat = this._getInternalFormat(format);
  13616. if (internalFormat === gl.RGB) {
  13617. internalFormat = gl.RGBA;
  13618. }
  13619. var width = size;
  13620. var height = width;
  13621. texture.width = width;
  13622. texture.height = height;
  13623. // Double check on POT to generate Mips.
  13624. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13625. if (!isPot) {
  13626. generateMipMaps = false;
  13627. }
  13628. // Upload data if needed. The texture won't be ready until then.
  13629. if (data) {
  13630. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  13631. }
  13632. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13633. // Filters
  13634. if (data && generateMipMaps) {
  13635. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13636. }
  13637. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  13638. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13639. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13640. }
  13641. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  13642. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13643. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13644. }
  13645. else {
  13646. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13647. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13648. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13649. }
  13650. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13651. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13652. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13653. return texture;
  13654. };
  13655. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  13656. var _this = this;
  13657. if (onLoad === void 0) { onLoad = null; }
  13658. if (onError === void 0) { onError = null; }
  13659. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13660. if (invertY === void 0) { invertY = false; }
  13661. var gl = this._gl;
  13662. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  13663. scene._addPendingData(texture);
  13664. texture.url = url;
  13665. this._internalTexturesCache.push(texture);
  13666. var onerror = function (request, exception) {
  13667. scene._removePendingData(texture);
  13668. if (onError && request) {
  13669. onError(request.status + " " + request.statusText, exception);
  13670. }
  13671. };
  13672. var internalCallback = function (data) {
  13673. var width = texture.width;
  13674. var faceDataArrays = callback(data);
  13675. if (!faceDataArrays) {
  13676. return;
  13677. }
  13678. if (mipmmapGenerator) {
  13679. var textureType = _this._getWebGLTextureType(type);
  13680. var internalFormat = _this._getInternalFormat(format);
  13681. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  13682. var needConversion = false;
  13683. if (internalFormat === gl.RGB) {
  13684. internalFormat = gl.RGBA;
  13685. needConversion = true;
  13686. }
  13687. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13688. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13689. var mipData = mipmmapGenerator(faceDataArrays);
  13690. for (var level = 0; level < mipData.length; level++) {
  13691. var mipSize = width >> level;
  13692. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13693. var mipFaceData = mipData[level][faceIndex];
  13694. if (needConversion) {
  13695. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  13696. }
  13697. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  13698. }
  13699. }
  13700. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13701. }
  13702. else {
  13703. texture.generateMipMaps = !noMipmap;
  13704. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  13705. }
  13706. texture.isReady = true;
  13707. // this.resetTextureCache();
  13708. scene._removePendingData(texture);
  13709. if (onLoad) {
  13710. onLoad();
  13711. }
  13712. };
  13713. this._loadFile(url, function (data) {
  13714. internalCallback(data);
  13715. }, undefined, scene.database, true, onerror);
  13716. return texture;
  13717. };
  13718. ;
  13719. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  13720. if (compression === void 0) { compression = null; }
  13721. var internalFormat = this._getInternalFormat(format);
  13722. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13723. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13724. if (!this._doNotHandleContextLost) {
  13725. texture._bufferView = data;
  13726. texture.format = format;
  13727. texture.invertY = invertY;
  13728. texture._compression = compression;
  13729. }
  13730. if (texture.width % 4 !== 0) {
  13731. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13732. }
  13733. if (compression && data) {
  13734. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  13735. }
  13736. else {
  13737. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  13738. }
  13739. if (texture.generateMipMaps) {
  13740. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13741. }
  13742. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13743. // this.resetTextureCache();
  13744. texture.isReady = true;
  13745. };
  13746. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  13747. if (compression === void 0) { compression = null; }
  13748. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  13749. texture.baseWidth = width;
  13750. texture.baseHeight = height;
  13751. texture.baseDepth = depth;
  13752. texture.width = width;
  13753. texture.height = height;
  13754. texture.depth = depth;
  13755. texture.format = format;
  13756. texture.generateMipMaps = generateMipMaps;
  13757. texture.samplingMode = samplingMode;
  13758. texture.is3D = true;
  13759. if (!this._doNotHandleContextLost) {
  13760. texture._bufferView = data;
  13761. }
  13762. this.updateRawTexture3D(texture, data, format, invertY, compression);
  13763. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13764. // Filters
  13765. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13766. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13767. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13768. if (generateMipMaps) {
  13769. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13770. }
  13771. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13772. this._internalTexturesCache.push(texture);
  13773. return texture;
  13774. };
  13775. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  13776. var gl = this._gl;
  13777. if (!gl) {
  13778. return;
  13779. }
  13780. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  13781. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13782. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13783. if (!noMipmap && !isCompressed) {
  13784. gl.generateMipmap(gl.TEXTURE_2D);
  13785. }
  13786. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13787. // this.resetTextureCache();
  13788. if (scene) {
  13789. scene._removePendingData(texture);
  13790. }
  13791. texture.onLoadedObservable.notifyObservers(texture);
  13792. texture.onLoadedObservable.clear();
  13793. };
  13794. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  13795. var _this = this;
  13796. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13797. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  13798. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  13799. var gl = this._gl;
  13800. if (!gl) {
  13801. return;
  13802. }
  13803. if (!texture._webGLTexture) {
  13804. // this.resetTextureCache();
  13805. if (scene) {
  13806. scene._removePendingData(texture);
  13807. }
  13808. return;
  13809. }
  13810. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13811. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13812. texture.baseWidth = width;
  13813. texture.baseHeight = height;
  13814. texture.width = potWidth;
  13815. texture.height = potHeight;
  13816. texture.isReady = true;
  13817. if (processFunction(potWidth, potHeight, function () {
  13818. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13819. })) {
  13820. // Returning as texture needs extra async steps
  13821. return;
  13822. }
  13823. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13824. };
  13825. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  13826. // Create new RGBA data container.
  13827. var rgbaData;
  13828. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  13829. rgbaData = new Float32Array(width * height * 4);
  13830. }
  13831. else {
  13832. rgbaData = new Uint32Array(width * height * 4);
  13833. }
  13834. // Convert each pixel.
  13835. for (var x = 0; x < width; x++) {
  13836. for (var y = 0; y < height; y++) {
  13837. var index = (y * width + x) * 3;
  13838. var newIndex = (y * width + x) * 4;
  13839. // Map Old Value to new value.
  13840. rgbaData[newIndex + 0] = rgbData[index + 0];
  13841. rgbaData[newIndex + 1] = rgbData[index + 1];
  13842. rgbaData[newIndex + 2] = rgbData[index + 2];
  13843. // Add fully opaque alpha channel.
  13844. rgbaData[newIndex + 3] = 1;
  13845. }
  13846. }
  13847. return rgbaData;
  13848. };
  13849. Engine.prototype._releaseFramebufferObjects = function (texture) {
  13850. var gl = this._gl;
  13851. if (texture._framebuffer) {
  13852. gl.deleteFramebuffer(texture._framebuffer);
  13853. texture._framebuffer = null;
  13854. }
  13855. if (texture._depthStencilBuffer) {
  13856. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13857. texture._depthStencilBuffer = null;
  13858. }
  13859. if (texture._MSAAFramebuffer) {
  13860. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13861. texture._MSAAFramebuffer = null;
  13862. }
  13863. if (texture._MSAARenderBuffer) {
  13864. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13865. texture._MSAARenderBuffer = null;
  13866. }
  13867. };
  13868. Engine.prototype._releaseTexture = function (texture) {
  13869. var gl = this._gl;
  13870. this._releaseFramebufferObjects(texture);
  13871. gl.deleteTexture(texture._webGLTexture);
  13872. // Unbind channels
  13873. this.unbindAllTextures();
  13874. var index = this._internalTexturesCache.indexOf(texture);
  13875. if (index !== -1) {
  13876. this._internalTexturesCache.splice(index, 1);
  13877. }
  13878. // Integrated fixed lod samplers.
  13879. if (texture._lodTextureHigh) {
  13880. texture._lodTextureHigh.dispose();
  13881. }
  13882. if (texture._lodTextureMid) {
  13883. texture._lodTextureMid.dispose();
  13884. }
  13885. if (texture._lodTextureLow) {
  13886. texture._lodTextureLow.dispose();
  13887. }
  13888. };
  13889. Engine.prototype.setProgram = function (program) {
  13890. if (this._currentProgram !== program) {
  13891. this._gl.useProgram(program);
  13892. this._currentProgram = program;
  13893. }
  13894. };
  13895. Engine.prototype.bindSamplers = function (effect) {
  13896. this.setProgram(effect.getProgram());
  13897. var samplers = effect.getSamplers();
  13898. for (var index = 0; index < samplers.length; index++) {
  13899. var uniform = effect.getUniform(samplers[index]);
  13900. if (uniform) {
  13901. this._boundUniforms[index] = uniform;
  13902. }
  13903. }
  13904. this._currentEffect = null;
  13905. };
  13906. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  13907. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  13908. return;
  13909. }
  13910. // Remove
  13911. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13912. // Bind last to it
  13913. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  13914. // Bind to dummy
  13915. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  13916. };
  13917. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  13918. if (!internalTexture) {
  13919. return -1;
  13920. }
  13921. internalTexture._initialSlot = channel;
  13922. if (this.disableTextureBindingOptimization) {
  13923. if (channel !== internalTexture._designatedSlot) {
  13924. this._textureCollisions.addCount(1, false);
  13925. }
  13926. }
  13927. else {
  13928. if (channel !== internalTexture._designatedSlot) {
  13929. if (internalTexture._designatedSlot > -1) {
  13930. return internalTexture._designatedSlot;
  13931. }
  13932. else {
  13933. // No slot for this texture, let's pick a new one (if we find a free slot)
  13934. if (this._nextFreeTextureSlots.length) {
  13935. return this._nextFreeTextureSlots[0];
  13936. }
  13937. // We need to recycle the oldest bound texture, sorry.
  13938. this._textureCollisions.addCount(1, false);
  13939. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  13940. }
  13941. }
  13942. }
  13943. return channel;
  13944. };
  13945. Engine.prototype._linkTrackers = function (previous, next) {
  13946. previous.next = next;
  13947. next.previous = previous;
  13948. };
  13949. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  13950. var currentSlot = internalTexture._designatedSlot;
  13951. if (currentSlot === -1) {
  13952. return -1;
  13953. }
  13954. internalTexture._designatedSlot = -1;
  13955. if (this.disableTextureBindingOptimization) {
  13956. return -1;
  13957. }
  13958. // Remove from bound list
  13959. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13960. // Free the slot
  13961. this._boundTexturesCache[currentSlot] = null;
  13962. this._nextFreeTextureSlots.push(currentSlot);
  13963. return currentSlot;
  13964. };
  13965. Engine.prototype._activateCurrentTexture = function () {
  13966. if (this._currentTextureChannel !== this._activeChannel) {
  13967. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  13968. this._currentTextureChannel = this._activeChannel;
  13969. }
  13970. };
  13971. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  13972. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  13973. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  13974. this._activeChannel = texture._designatedSlot;
  13975. }
  13976. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  13977. var isTextureForRendering = texture && texture._initialSlot > -1;
  13978. if (currentTextureBound !== texture) {
  13979. if (currentTextureBound) {
  13980. this._removeDesignatedSlot(currentTextureBound);
  13981. }
  13982. this._activateCurrentTexture();
  13983. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  13984. this._boundTexturesCache[this._activeChannel] = texture;
  13985. if (texture) {
  13986. if (!this.disableTextureBindingOptimization) {
  13987. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  13988. if (slotIndex > -1) {
  13989. this._nextFreeTextureSlots.splice(slotIndex, 1);
  13990. }
  13991. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  13992. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  13993. }
  13994. texture._designatedSlot = this._activeChannel;
  13995. }
  13996. }
  13997. else if (forTextureDataUpdate) {
  13998. this._activateCurrentTexture();
  13999. }
  14000. if (isTextureForRendering && !forTextureDataUpdate) {
  14001. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14002. }
  14003. };
  14004. Engine.prototype._bindTexture = function (channel, texture) {
  14005. if (channel < 0) {
  14006. return;
  14007. }
  14008. if (texture) {
  14009. channel = this._getCorrectTextureChannel(channel, texture);
  14010. }
  14011. this._activeChannel = channel;
  14012. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14013. };
  14014. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14015. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14016. };
  14017. Engine.prototype.unbindAllTextures = function () {
  14018. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14019. this._activeChannel = channel;
  14020. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14021. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14022. if (this.webGLVersion > 1) {
  14023. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14024. }
  14025. }
  14026. };
  14027. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14028. if (channel < 0) {
  14029. return;
  14030. }
  14031. if (uniform) {
  14032. this._boundUniforms[channel] = uniform;
  14033. }
  14034. this._setTexture(channel, texture);
  14035. };
  14036. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14037. var uniform = this._boundUniforms[sourceSlot];
  14038. if (uniform._currentState === destination) {
  14039. return;
  14040. }
  14041. this._gl.uniform1i(uniform, destination);
  14042. uniform._currentState = destination;
  14043. };
  14044. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14045. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14046. // Not ready?
  14047. if (!texture) {
  14048. if (this._boundTexturesCache[channel] != null) {
  14049. this._activeChannel = channel;
  14050. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14051. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14052. if (this.webGLVersion > 1) {
  14053. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14054. }
  14055. }
  14056. return false;
  14057. }
  14058. // Video
  14059. if (texture.video) {
  14060. this._activeChannel = channel;
  14061. texture.update();
  14062. }
  14063. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14064. texture.delayLoad();
  14065. return false;
  14066. }
  14067. var internalTexture;
  14068. if (texture.isReady()) {
  14069. internalTexture = texture.getInternalTexture();
  14070. }
  14071. else if (texture.isCube) {
  14072. internalTexture = this.emptyCubeTexture;
  14073. }
  14074. else if (texture.is3D) {
  14075. internalTexture = this.emptyTexture3D;
  14076. }
  14077. else {
  14078. internalTexture = this.emptyTexture;
  14079. }
  14080. if (!isPartOfTextureArray) {
  14081. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14082. }
  14083. if (this._boundTexturesCache[channel] === internalTexture) {
  14084. this._moveBoundTextureOnTop(internalTexture);
  14085. if (!isPartOfTextureArray) {
  14086. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14087. }
  14088. return false;
  14089. }
  14090. this._activeChannel = channel;
  14091. if (internalTexture && internalTexture.is3D) {
  14092. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14093. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14094. internalTexture._cachedWrapU = texture.wrapU;
  14095. switch (texture.wrapU) {
  14096. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14097. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14098. break;
  14099. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14100. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14101. break;
  14102. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14103. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14104. break;
  14105. }
  14106. }
  14107. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14108. internalTexture._cachedWrapV = texture.wrapV;
  14109. switch (texture.wrapV) {
  14110. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14111. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14112. break;
  14113. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14114. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14115. break;
  14116. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14117. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14118. break;
  14119. }
  14120. }
  14121. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14122. internalTexture._cachedWrapR = texture.wrapR;
  14123. switch (texture.wrapV) {
  14124. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14125. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14126. break;
  14127. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14128. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14129. break;
  14130. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14131. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14132. break;
  14133. }
  14134. }
  14135. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14136. }
  14137. else if (internalTexture && internalTexture.isCube) {
  14138. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14139. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14140. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14141. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14142. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14143. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14144. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14145. }
  14146. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14147. }
  14148. else {
  14149. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14150. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14151. internalTexture._cachedWrapU = texture.wrapU;
  14152. switch (texture.wrapU) {
  14153. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14154. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14155. break;
  14156. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14157. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14158. break;
  14159. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14160. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14161. break;
  14162. }
  14163. }
  14164. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14165. internalTexture._cachedWrapV = texture.wrapV;
  14166. switch (texture.wrapV) {
  14167. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14168. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14169. break;
  14170. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14171. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14172. break;
  14173. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14174. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14175. break;
  14176. }
  14177. }
  14178. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14179. }
  14180. return true;
  14181. };
  14182. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14183. if (channel < 0 || !uniform) {
  14184. return;
  14185. }
  14186. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14187. this._textureUnits = new Int32Array(textures.length);
  14188. }
  14189. for (var i = 0; i < textures.length; i++) {
  14190. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14191. }
  14192. this._gl.uniform1iv(uniform, this._textureUnits);
  14193. for (var index = 0; index < textures.length; index++) {
  14194. this._setTexture(this._textureUnits[index], textures[index], true);
  14195. }
  14196. };
  14197. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14198. var internalTexture = texture.getInternalTexture();
  14199. if (!internalTexture) {
  14200. return;
  14201. }
  14202. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14203. var value = texture.anisotropicFilteringLevel;
  14204. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14205. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14206. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14207. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14208. }
  14209. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14210. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14211. internalTexture._cachedAnisotropicFilteringLevel = value;
  14212. }
  14213. };
  14214. Engine.prototype.readPixels = function (x, y, width, height) {
  14215. var data = new Uint8Array(height * width * 4);
  14216. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14217. return data;
  14218. };
  14219. /**
  14220. * Add an externaly attached data from its key.
  14221. * This method call will fail and return false, if such key already exists.
  14222. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14223. * @param key the unique key that identifies the data
  14224. * @param data the data object to associate to the key for this Engine instance
  14225. * @return true if no such key were already present and the data was added successfully, false otherwise
  14226. */
  14227. Engine.prototype.addExternalData = function (key, data) {
  14228. if (!this._externalData) {
  14229. this._externalData = new BABYLON.StringDictionary();
  14230. }
  14231. return this._externalData.add(key, data);
  14232. };
  14233. /**
  14234. * Get an externaly attached data from its key
  14235. * @param key the unique key that identifies the data
  14236. * @return the associated data, if present (can be null), or undefined if not present
  14237. */
  14238. Engine.prototype.getExternalData = function (key) {
  14239. if (!this._externalData) {
  14240. this._externalData = new BABYLON.StringDictionary();
  14241. }
  14242. return this._externalData.get(key);
  14243. };
  14244. /**
  14245. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14246. * @param key the unique key that identifies the data
  14247. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14248. * @return the associated data, can be null if the factory returned null.
  14249. */
  14250. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14251. if (!this._externalData) {
  14252. this._externalData = new BABYLON.StringDictionary();
  14253. }
  14254. return this._externalData.getOrAddWithFactory(key, factory);
  14255. };
  14256. /**
  14257. * Remove an externaly attached data from the Engine instance
  14258. * @param key the unique key that identifies the data
  14259. * @return true if the data was successfully removed, false if it doesn't exist
  14260. */
  14261. Engine.prototype.removeExternalData = function (key) {
  14262. if (!this._externalData) {
  14263. this._externalData = new BABYLON.StringDictionary();
  14264. }
  14265. return this._externalData.remove(key);
  14266. };
  14267. Engine.prototype.unbindAllAttributes = function () {
  14268. if (this._mustWipeVertexAttributes) {
  14269. this._mustWipeVertexAttributes = false;
  14270. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14271. this._gl.disableVertexAttribArray(i);
  14272. this._vertexAttribArraysEnabled[i] = false;
  14273. this._currentBufferPointers[i].active = false;
  14274. }
  14275. return;
  14276. }
  14277. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14278. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14279. continue;
  14280. }
  14281. this._gl.disableVertexAttribArray(i);
  14282. this._vertexAttribArraysEnabled[i] = false;
  14283. this._currentBufferPointers[i].active = false;
  14284. }
  14285. };
  14286. Engine.prototype.releaseEffects = function () {
  14287. for (var name in this._compiledEffects) {
  14288. this._deleteProgram(this._compiledEffects[name]._program);
  14289. }
  14290. this._compiledEffects = {};
  14291. };
  14292. // Dispose
  14293. Engine.prototype.dispose = function () {
  14294. this.hideLoadingUI();
  14295. this.stopRenderLoop();
  14296. // Release postProcesses
  14297. while (this.postProcesses.length) {
  14298. this.postProcesses[0].dispose();
  14299. }
  14300. // Empty texture
  14301. if (this._emptyTexture) {
  14302. this._releaseTexture(this._emptyTexture);
  14303. this._emptyTexture = null;
  14304. }
  14305. if (this._emptyCubeTexture) {
  14306. this._releaseTexture(this._emptyCubeTexture);
  14307. this._emptyCubeTexture = null;
  14308. }
  14309. // Rescale PP
  14310. if (this._rescalePostProcess) {
  14311. this._rescalePostProcess.dispose();
  14312. }
  14313. // Release scenes
  14314. while (this.scenes.length) {
  14315. this.scenes[0].dispose();
  14316. }
  14317. // Release audio engine
  14318. if (Engine.audioEngine) {
  14319. Engine.audioEngine.dispose();
  14320. }
  14321. // Release effects
  14322. this.releaseEffects();
  14323. // Unbind
  14324. this.unbindAllAttributes();
  14325. if (this._dummyFramebuffer) {
  14326. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14327. }
  14328. //WebVR
  14329. this.disableVR();
  14330. // Events
  14331. if (BABYLON.Tools.IsWindowObjectExist()) {
  14332. window.removeEventListener("blur", this._onBlur);
  14333. window.removeEventListener("focus", this._onFocus);
  14334. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14335. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14336. if (this._renderingCanvas) {
  14337. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14338. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14339. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  14340. if (!this._doNotHandleContextLost) {
  14341. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14342. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14343. }
  14344. }
  14345. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14346. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14347. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14348. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14349. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14350. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14351. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14352. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14353. if (this._onVrDisplayConnect) {
  14354. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14355. if (this._onVrDisplayDisconnect) {
  14356. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14357. }
  14358. if (this._onVrDisplayPresentChange) {
  14359. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14360. }
  14361. this._onVrDisplayConnect = null;
  14362. this._onVrDisplayDisconnect = null;
  14363. }
  14364. }
  14365. // Remove from Instances
  14366. var index = Engine.Instances.indexOf(this);
  14367. if (index >= 0) {
  14368. Engine.Instances.splice(index, 1);
  14369. }
  14370. this._workingCanvas = null;
  14371. this._workingContext = null;
  14372. this._currentBufferPointers = [];
  14373. this._renderingCanvas = null;
  14374. this._currentProgram = null;
  14375. this.onResizeObservable.clear();
  14376. this.onCanvasBlurObservable.clear();
  14377. this.onCanvasFocusObservable.clear();
  14378. this.onCanvasPointerOutObservable.clear();
  14379. this.onBeginFrameObservable.clear();
  14380. this.onEndFrameObservable.clear();
  14381. BABYLON.Effect.ResetCache();
  14382. // Abort active requests
  14383. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14384. var request = _a[_i];
  14385. request.abort();
  14386. }
  14387. };
  14388. // Loading screen
  14389. Engine.prototype.displayLoadingUI = function () {
  14390. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14391. return;
  14392. }
  14393. var loadingScreen = this.loadingScreen;
  14394. if (loadingScreen) {
  14395. loadingScreen.displayLoadingUI();
  14396. }
  14397. };
  14398. Engine.prototype.hideLoadingUI = function () {
  14399. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14400. return;
  14401. }
  14402. var loadingScreen = this.loadingScreen;
  14403. if (loadingScreen) {
  14404. loadingScreen.hideLoadingUI();
  14405. }
  14406. };
  14407. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14408. get: function () {
  14409. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14410. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14411. return this._loadingScreen;
  14412. },
  14413. set: function (loadingScreen) {
  14414. this._loadingScreen = loadingScreen;
  14415. },
  14416. enumerable: true,
  14417. configurable: true
  14418. });
  14419. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14420. set: function (text) {
  14421. this.loadingScreen.loadingUIText = text;
  14422. },
  14423. enumerable: true,
  14424. configurable: true
  14425. });
  14426. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14427. set: function (color) {
  14428. this.loadingScreen.loadingUIBackgroundColor = color;
  14429. },
  14430. enumerable: true,
  14431. configurable: true
  14432. });
  14433. Engine.prototype.attachContextLostEvent = function (callback) {
  14434. if (this._renderingCanvas) {
  14435. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14436. }
  14437. };
  14438. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14439. if (this._renderingCanvas) {
  14440. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14441. }
  14442. };
  14443. Engine.prototype.getVertexShaderSource = function (program) {
  14444. var shaders = this._gl.getAttachedShaders(program);
  14445. if (!shaders) {
  14446. return null;
  14447. }
  14448. return this._gl.getShaderSource(shaders[0]);
  14449. };
  14450. Engine.prototype.getFragmentShaderSource = function (program) {
  14451. var shaders = this._gl.getAttachedShaders(program);
  14452. if (!shaders) {
  14453. return null;
  14454. }
  14455. return this._gl.getShaderSource(shaders[1]);
  14456. };
  14457. Engine.prototype.getError = function () {
  14458. return this._gl.getError();
  14459. };
  14460. // FPS
  14461. Engine.prototype.getFps = function () {
  14462. return this._fps;
  14463. };
  14464. Engine.prototype.getDeltaTime = function () {
  14465. return this._deltaTime;
  14466. };
  14467. Engine.prototype._measureFps = function () {
  14468. this._performanceMonitor.sampleFrame();
  14469. this._fps = this._performanceMonitor.averageFPS;
  14470. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  14471. };
  14472. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  14473. if (faceIndex === void 0) { faceIndex = -1; }
  14474. var gl = this._gl;
  14475. if (!this._dummyFramebuffer) {
  14476. var dummy = gl.createFramebuffer();
  14477. if (!dummy) {
  14478. throw new Error("Unable to create dummy framebuffer");
  14479. }
  14480. this._dummyFramebuffer = dummy;
  14481. }
  14482. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  14483. if (faceIndex > -1) {
  14484. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  14485. }
  14486. else {
  14487. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14488. }
  14489. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  14490. var buffer;
  14491. switch (readType) {
  14492. case gl.UNSIGNED_BYTE:
  14493. buffer = new Uint8Array(4 * width * height);
  14494. readType = gl.UNSIGNED_BYTE;
  14495. break;
  14496. default:
  14497. buffer = new Float32Array(4 * width * height);
  14498. readType = gl.FLOAT;
  14499. break;
  14500. }
  14501. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  14502. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  14503. return buffer;
  14504. };
  14505. Engine.prototype._canRenderToFloatFramebuffer = function () {
  14506. if (this._webGLVersion > 1) {
  14507. return this._caps.colorBufferFloat;
  14508. }
  14509. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  14510. };
  14511. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  14512. if (this._webGLVersion > 1) {
  14513. return this._caps.colorBufferFloat;
  14514. }
  14515. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  14516. };
  14517. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  14518. Engine.prototype._canRenderToFramebuffer = function (type) {
  14519. var gl = this._gl;
  14520. //clear existing errors
  14521. while (gl.getError() !== gl.NO_ERROR) { }
  14522. var successful = true;
  14523. var texture = gl.createTexture();
  14524. gl.bindTexture(gl.TEXTURE_2D, texture);
  14525. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14526. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14527. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14528. var fb = gl.createFramebuffer();
  14529. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  14530. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  14531. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  14532. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  14533. successful = successful && (gl.getError() === gl.NO_ERROR);
  14534. //try render by clearing frame buffer's color buffer
  14535. if (successful) {
  14536. gl.clear(gl.COLOR_BUFFER_BIT);
  14537. successful = successful && (gl.getError() === gl.NO_ERROR);
  14538. }
  14539. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  14540. if (successful) {
  14541. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  14542. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14543. var readFormat = gl.RGBA;
  14544. var readType = gl.UNSIGNED_BYTE;
  14545. var buffer = new Uint8Array(4);
  14546. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  14547. successful = successful && (gl.getError() === gl.NO_ERROR);
  14548. }
  14549. //clean up
  14550. gl.deleteTexture(texture);
  14551. gl.deleteFramebuffer(fb);
  14552. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14553. //clear accumulated errors
  14554. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  14555. return successful;
  14556. };
  14557. Engine.prototype._getWebGLTextureType = function (type) {
  14558. if (type === Engine.TEXTURETYPE_FLOAT) {
  14559. return this._gl.FLOAT;
  14560. }
  14561. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14562. // Add Half Float Constant.
  14563. return this._gl.HALF_FLOAT_OES;
  14564. }
  14565. return this._gl.UNSIGNED_BYTE;
  14566. };
  14567. ;
  14568. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  14569. if (this._webGLVersion === 1) {
  14570. return this._gl.RGBA;
  14571. }
  14572. if (type === Engine.TEXTURETYPE_FLOAT) {
  14573. return this._gl.RGBA32F;
  14574. }
  14575. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14576. return this._gl.RGBA16F;
  14577. }
  14578. return this._gl.RGBA;
  14579. };
  14580. ;
  14581. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  14582. if (type === Engine.TEXTURETYPE_FLOAT) {
  14583. return this._gl.RGBA32F;
  14584. }
  14585. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14586. return this._gl.RGBA16F;
  14587. }
  14588. return this._gl.RGBA8;
  14589. };
  14590. ;
  14591. Engine.prototype.createQuery = function () {
  14592. return this._gl.createQuery();
  14593. };
  14594. Engine.prototype.deleteQuery = function (query) {
  14595. this._gl.deleteQuery(query);
  14596. return this;
  14597. };
  14598. Engine.prototype.isQueryResultAvailable = function (query) {
  14599. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  14600. };
  14601. Engine.prototype.getQueryResult = function (query) {
  14602. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  14603. };
  14604. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  14605. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14606. this._gl.beginQuery(glAlgorithm, query);
  14607. return this;
  14608. };
  14609. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  14610. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14611. this._gl.endQuery(glAlgorithm);
  14612. return this;
  14613. };
  14614. /* Time queries */
  14615. Engine.prototype._createTimeQuery = function () {
  14616. var timerQuery = this._caps.timerQuery;
  14617. if (timerQuery.createQueryEXT) {
  14618. return timerQuery.createQueryEXT();
  14619. }
  14620. return this.createQuery();
  14621. };
  14622. Engine.prototype._deleteTimeQuery = function (query) {
  14623. var timerQuery = this._caps.timerQuery;
  14624. if (timerQuery.deleteQueryEXT) {
  14625. timerQuery.deleteQueryEXT(query);
  14626. return;
  14627. }
  14628. this.deleteQuery(query);
  14629. };
  14630. Engine.prototype._getTimeQueryResult = function (query) {
  14631. var timerQuery = this._caps.timerQuery;
  14632. if (timerQuery.getQueryObjectEXT) {
  14633. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  14634. }
  14635. return this.getQueryResult(query);
  14636. };
  14637. Engine.prototype._getTimeQueryAvailability = function (query) {
  14638. var timerQuery = this._caps.timerQuery;
  14639. if (timerQuery.getQueryObjectEXT) {
  14640. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  14641. }
  14642. return this.isQueryResultAvailable(query);
  14643. };
  14644. Engine.prototype.startTimeQuery = function () {
  14645. var timerQuery = this._caps.timerQuery;
  14646. if (!timerQuery) {
  14647. return null;
  14648. }
  14649. var token = new BABYLON._TimeToken();
  14650. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14651. if (this._caps.canUseTimestampForTimerQuery) {
  14652. token._startTimeQuery = this._createTimeQuery();
  14653. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  14654. }
  14655. else {
  14656. if (this._currentNonTimestampToken) {
  14657. return this._currentNonTimestampToken;
  14658. }
  14659. token._timeElapsedQuery = this._createTimeQuery();
  14660. if (timerQuery.beginQueryEXT) {
  14661. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14662. }
  14663. else {
  14664. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14665. }
  14666. this._currentNonTimestampToken = token;
  14667. }
  14668. return token;
  14669. };
  14670. Engine.prototype.endTimeQuery = function (token) {
  14671. var timerQuery = this._caps.timerQuery;
  14672. if (!timerQuery || !token) {
  14673. return -1;
  14674. }
  14675. if (this._caps.canUseTimestampForTimerQuery) {
  14676. if (!token._startTimeQuery) {
  14677. return -1;
  14678. }
  14679. if (!token._endTimeQuery) {
  14680. token._endTimeQuery = this._createTimeQuery();
  14681. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  14682. }
  14683. }
  14684. else if (!token._timeElapsedQueryEnded) {
  14685. if (!token._timeElapsedQuery) {
  14686. return -1;
  14687. }
  14688. if (timerQuery.endQueryEXT) {
  14689. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  14690. }
  14691. else {
  14692. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  14693. }
  14694. token._timeElapsedQueryEnded = true;
  14695. }
  14696. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14697. var available = false;
  14698. if (token._endTimeQuery) {
  14699. available = this._getTimeQueryAvailability(token._endTimeQuery);
  14700. }
  14701. else if (token._timeElapsedQuery) {
  14702. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  14703. }
  14704. if (available && !disjoint) {
  14705. var result = 0;
  14706. if (this._caps.canUseTimestampForTimerQuery) {
  14707. if (!token._startTimeQuery || !token._endTimeQuery) {
  14708. return -1;
  14709. }
  14710. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  14711. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  14712. result = timeEnd - timeStart;
  14713. this._deleteTimeQuery(token._startTimeQuery);
  14714. this._deleteTimeQuery(token._endTimeQuery);
  14715. token._startTimeQuery = null;
  14716. token._endTimeQuery = null;
  14717. }
  14718. else {
  14719. if (!token._timeElapsedQuery) {
  14720. return -1;
  14721. }
  14722. result = this._getTimeQueryResult(token._timeElapsedQuery);
  14723. this._deleteTimeQuery(token._timeElapsedQuery);
  14724. token._timeElapsedQuery = null;
  14725. token._timeElapsedQueryEnded = false;
  14726. this._currentNonTimestampToken = null;
  14727. }
  14728. return result;
  14729. }
  14730. return -1;
  14731. };
  14732. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  14733. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  14734. };
  14735. // Transform feedback
  14736. Engine.prototype.createTransformFeedback = function () {
  14737. return this._gl.createTransformFeedback();
  14738. };
  14739. Engine.prototype.deleteTransformFeedback = function (value) {
  14740. this._gl.deleteTransformFeedback(value);
  14741. };
  14742. Engine.prototype.bindTransformFeedback = function (value) {
  14743. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  14744. };
  14745. Engine.prototype.beginTransformFeedback = function (usePoints) {
  14746. if (usePoints === void 0) { usePoints = true; }
  14747. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  14748. };
  14749. Engine.prototype.endTransformFeedback = function () {
  14750. this._gl.endTransformFeedback();
  14751. };
  14752. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  14753. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  14754. };
  14755. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  14756. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  14757. };
  14758. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  14759. var _this = this;
  14760. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  14761. this._activeRequests.push(request);
  14762. request.onCompleteObservable.add(function (request) {
  14763. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  14764. });
  14765. return request;
  14766. };
  14767. /** @ignore */
  14768. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  14769. var _this = this;
  14770. return new Promise(function (resolve, reject) {
  14771. _this._loadFile(url, function (data) {
  14772. resolve(data);
  14773. }, undefined, database, useArrayBuffer, function (request, exception) {
  14774. reject(exception);
  14775. });
  14776. });
  14777. };
  14778. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  14779. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14780. var onload = function (data) {
  14781. loadedFiles[index] = data;
  14782. loadedFiles._internalCount++;
  14783. if (loadedFiles._internalCount === 6) {
  14784. onfinish(loadedFiles);
  14785. }
  14786. };
  14787. var onerror = function (request, exception) {
  14788. if (onErrorCallBack && request) {
  14789. onErrorCallBack(request.status + " " + request.statusText, exception);
  14790. }
  14791. };
  14792. this._loadFile(url, onload, undefined, undefined, true, onerror);
  14793. };
  14794. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  14795. if (onError === void 0) { onError = null; }
  14796. var loadedFiles = [];
  14797. loadedFiles._internalCount = 0;
  14798. for (var index = 0; index < 6; index++) {
  14799. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  14800. }
  14801. };
  14802. // Statics
  14803. Engine.isSupported = function () {
  14804. try {
  14805. var tempcanvas = document.createElement("canvas");
  14806. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  14807. return gl != null && !!window.WebGLRenderingContext;
  14808. }
  14809. catch (e) {
  14810. return false;
  14811. }
  14812. };
  14813. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  14814. Engine.ExceptionList = [
  14815. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  14816. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  14817. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14818. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14819. ];
  14820. Engine.Instances = new Array();
  14821. // Const statics
  14822. Engine._ALPHA_DISABLE = 0;
  14823. Engine._ALPHA_ADD = 1;
  14824. Engine._ALPHA_COMBINE = 2;
  14825. Engine._ALPHA_SUBTRACT = 3;
  14826. Engine._ALPHA_MULTIPLY = 4;
  14827. Engine._ALPHA_MAXIMIZED = 5;
  14828. Engine._ALPHA_ONEONE = 6;
  14829. Engine._ALPHA_PREMULTIPLIED = 7;
  14830. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  14831. Engine._ALPHA_INTERPOLATE = 9;
  14832. Engine._ALPHA_SCREENMODE = 10;
  14833. Engine._DELAYLOADSTATE_NONE = 0;
  14834. Engine._DELAYLOADSTATE_LOADED = 1;
  14835. Engine._DELAYLOADSTATE_LOADING = 2;
  14836. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  14837. Engine._TEXTUREFORMAT_ALPHA = 0;
  14838. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  14839. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  14840. Engine._TEXTUREFORMAT_RGB = 4;
  14841. Engine._TEXTUREFORMAT_RGBA = 5;
  14842. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  14843. Engine._TEXTURETYPE_FLOAT = 1;
  14844. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  14845. // Depht or Stencil test Constants.
  14846. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  14847. 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.
  14848. 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.
  14849. 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.
  14850. 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.
  14851. 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.
  14852. 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.
  14853. 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.
  14854. // Stencil Actions Constants.
  14855. Engine._KEEP = 0x1E00;
  14856. Engine._REPLACE = 0x1E01;
  14857. Engine._INCR = 0x1E02;
  14858. Engine._DECR = 0x1E03;
  14859. Engine._INVERT = 0x150A;
  14860. Engine._INCR_WRAP = 0x8507;
  14861. Engine._DECR_WRAP = 0x8508;
  14862. // Texture rescaling mode
  14863. Engine._SCALEMODE_FLOOR = 1;
  14864. Engine._SCALEMODE_NEAREST = 2;
  14865. Engine._SCALEMODE_CEILING = 3;
  14866. // Updatable statics so stick with vars here
  14867. Engine.CollisionsEpsilon = 0.001;
  14868. Engine.CodeRepository = "src/";
  14869. Engine.ShadersRepository = "src/Shaders/";
  14870. return Engine;
  14871. }());
  14872. BABYLON.Engine = Engine;
  14873. })(BABYLON || (BABYLON = {}));
  14874. //# sourceMappingURL=babylon.engine.js.map
  14875. var BABYLON;
  14876. (function (BABYLON) {
  14877. /**
  14878. * Node is the basic class for all scene objects (Mesh, Light Camera).
  14879. */
  14880. var Node = /** @class */ (function () {
  14881. /**
  14882. * @constructor
  14883. * @param {string} name - the name and id to be given to this node
  14884. * @param {BABYLON.Scene} the scene this node will be added to
  14885. */
  14886. function Node(name, scene) {
  14887. if (scene === void 0) { scene = null; }
  14888. this.state = "";
  14889. this.metadata = null;
  14890. this.doNotSerialize = false;
  14891. this.animations = new Array();
  14892. this._ranges = {};
  14893. this._isEnabled = true;
  14894. this._isReady = true;
  14895. this._currentRenderId = -1;
  14896. this._parentRenderId = -1;
  14897. /**
  14898. * An event triggered when the mesh is disposed.
  14899. * @type {BABYLON.Observable}
  14900. */
  14901. this.onDisposeObservable = new BABYLON.Observable();
  14902. // Behaviors
  14903. this._behaviors = new Array();
  14904. this.name = name;
  14905. this.id = name;
  14906. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  14907. this.uniqueId = this._scene.getUniqueId();
  14908. this._initCache();
  14909. }
  14910. Object.defineProperty(Node.prototype, "parent", {
  14911. get: function () {
  14912. return this._parentNode;
  14913. },
  14914. set: function (parent) {
  14915. if (this._parentNode === parent) {
  14916. return;
  14917. }
  14918. // Remove self from list of children of parent
  14919. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  14920. var index = this._parentNode._children.indexOf(this);
  14921. if (index !== -1) {
  14922. this._parentNode._children.splice(index, 1);
  14923. }
  14924. }
  14925. // Store new parent
  14926. this._parentNode = parent;
  14927. // Add as child to new parent
  14928. if (this._parentNode) {
  14929. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  14930. this._parentNode._children = new Array();
  14931. }
  14932. this._parentNode._children.push(this);
  14933. }
  14934. },
  14935. enumerable: true,
  14936. configurable: true
  14937. });
  14938. Node.prototype.getClassName = function () {
  14939. return "Node";
  14940. };
  14941. Object.defineProperty(Node.prototype, "onDispose", {
  14942. set: function (callback) {
  14943. if (this._onDisposeObserver) {
  14944. this.onDisposeObservable.remove(this._onDisposeObserver);
  14945. }
  14946. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14947. },
  14948. enumerable: true,
  14949. configurable: true
  14950. });
  14951. Node.prototype.getScene = function () {
  14952. return this._scene;
  14953. };
  14954. Node.prototype.getEngine = function () {
  14955. return this._scene.getEngine();
  14956. };
  14957. Node.prototype.addBehavior = function (behavior) {
  14958. var _this = this;
  14959. var index = this._behaviors.indexOf(behavior);
  14960. if (index !== -1) {
  14961. return this;
  14962. }
  14963. behavior.init();
  14964. if (this._scene.isLoading) {
  14965. // We defer the attach when the scene will be loaded
  14966. var observer = this._scene.onDataLoadedObservable.add(function () {
  14967. behavior.attach(_this);
  14968. setTimeout(function () {
  14969. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  14970. _this._scene.onDataLoadedObservable.remove(observer);
  14971. }, 0);
  14972. });
  14973. }
  14974. else {
  14975. behavior.attach(this);
  14976. }
  14977. this._behaviors.push(behavior);
  14978. return this;
  14979. };
  14980. Node.prototype.removeBehavior = function (behavior) {
  14981. var index = this._behaviors.indexOf(behavior);
  14982. if (index === -1) {
  14983. return this;
  14984. }
  14985. this._behaviors[index].detach();
  14986. this._behaviors.splice(index, 1);
  14987. return this;
  14988. };
  14989. Object.defineProperty(Node.prototype, "behaviors", {
  14990. get: function () {
  14991. return this._behaviors;
  14992. },
  14993. enumerable: true,
  14994. configurable: true
  14995. });
  14996. Node.prototype.getBehaviorByName = function (name) {
  14997. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  14998. var behavior = _a[_i];
  14999. if (behavior.name === name) {
  15000. return behavior;
  15001. }
  15002. }
  15003. return null;
  15004. };
  15005. // override it in derived class
  15006. Node.prototype.getWorldMatrix = function () {
  15007. return BABYLON.Matrix.Identity();
  15008. };
  15009. // override it in derived class if you add new variables to the cache
  15010. // and call the parent class method
  15011. Node.prototype._initCache = function () {
  15012. this._cache = {};
  15013. this._cache.parent = undefined;
  15014. };
  15015. Node.prototype.updateCache = function (force) {
  15016. if (!force && this.isSynchronized())
  15017. return;
  15018. this._cache.parent = this.parent;
  15019. this._updateCache();
  15020. };
  15021. // override it in derived class if you add new variables to the cache
  15022. // and call the parent class method if !ignoreParentClass
  15023. Node.prototype._updateCache = function (ignoreParentClass) {
  15024. };
  15025. // override it in derived class if you add new variables to the cache
  15026. Node.prototype._isSynchronized = function () {
  15027. return true;
  15028. };
  15029. Node.prototype._markSyncedWithParent = function () {
  15030. if (this.parent) {
  15031. this._parentRenderId = this.parent._currentRenderId;
  15032. }
  15033. };
  15034. Node.prototype.isSynchronizedWithParent = function () {
  15035. if (!this.parent) {
  15036. return true;
  15037. }
  15038. if (this._parentRenderId !== this.parent._currentRenderId) {
  15039. return false;
  15040. }
  15041. return this.parent.isSynchronized();
  15042. };
  15043. Node.prototype.isSynchronized = function (updateCache) {
  15044. var check = this.hasNewParent();
  15045. check = check || !this.isSynchronizedWithParent();
  15046. check = check || !this._isSynchronized();
  15047. if (updateCache)
  15048. this.updateCache(true);
  15049. return !check;
  15050. };
  15051. Node.prototype.hasNewParent = function (update) {
  15052. if (this._cache.parent === this.parent)
  15053. return false;
  15054. if (update)
  15055. this._cache.parent = this.parent;
  15056. return true;
  15057. };
  15058. /**
  15059. * Is this node ready to be used/rendered
  15060. * @return {boolean} is it ready
  15061. */
  15062. Node.prototype.isReady = function () {
  15063. return this._isReady;
  15064. };
  15065. /**
  15066. * Is this node enabled.
  15067. * 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.
  15068. * @param {boolean} [checkAncestors=true] - Indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors.
  15069. * @return {boolean} whether this node (and its parent) is enabled.
  15070. * @see setEnabled
  15071. */
  15072. Node.prototype.isEnabled = function (checkAncestors) {
  15073. if (checkAncestors === void 0) { checkAncestors = true; }
  15074. if (checkAncestors === false) {
  15075. return this._isEnabled;
  15076. }
  15077. if (this._isEnabled === false) {
  15078. return false;
  15079. }
  15080. if (this.parent !== undefined && this.parent !== null) {
  15081. return this.parent.isEnabled(checkAncestors);
  15082. }
  15083. return true;
  15084. };
  15085. /**
  15086. * Set the enabled state of this node.
  15087. * @param {boolean} value - the new enabled state
  15088. * @see isEnabled
  15089. */
  15090. Node.prototype.setEnabled = function (value) {
  15091. this._isEnabled = value;
  15092. };
  15093. /**
  15094. * Is this node a descendant of the given node.
  15095. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  15096. * @param {BABYLON.Node} ancestor - The parent node to inspect
  15097. * @see parent
  15098. */
  15099. Node.prototype.isDescendantOf = function (ancestor) {
  15100. if (this.parent) {
  15101. if (this.parent === ancestor) {
  15102. return true;
  15103. }
  15104. return this.parent.isDescendantOf(ancestor);
  15105. }
  15106. return false;
  15107. };
  15108. /**
  15109. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  15110. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  15111. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  15112. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  15113. */
  15114. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15115. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15116. if (!this._children) {
  15117. return;
  15118. }
  15119. for (var index = 0; index < this._children.length; index++) {
  15120. var item = this._children[index];
  15121. if (!predicate || predicate(item)) {
  15122. results.push(item);
  15123. }
  15124. if (!directDescendantsOnly) {
  15125. item._getDescendants(results, false, predicate);
  15126. }
  15127. }
  15128. };
  15129. /**
  15130. * Will return all nodes that have this node as ascendant.
  15131. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  15132. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  15133. * @return {BABYLON.Node[]} all children nodes of all types.
  15134. */
  15135. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15136. var results = new Array();
  15137. this._getDescendants(results, directDescendantsOnly, predicate);
  15138. return results;
  15139. };
  15140. /**
  15141. * Get all child-meshes of this node.
  15142. */
  15143. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15144. var results = [];
  15145. this._getDescendants(results, directDescendantsOnly, function (node) {
  15146. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15147. });
  15148. return results;
  15149. };
  15150. /**
  15151. * Get all child-transformNodes of this node.
  15152. */
  15153. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15154. var results = [];
  15155. this._getDescendants(results, directDescendantsOnly, function (node) {
  15156. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15157. });
  15158. return results;
  15159. };
  15160. /**
  15161. * Get all direct children of this node.
  15162. */
  15163. Node.prototype.getChildren = function (predicate) {
  15164. return this.getDescendants(true, predicate);
  15165. };
  15166. Node.prototype._setReady = function (state) {
  15167. if (state === this._isReady) {
  15168. return;
  15169. }
  15170. if (!state) {
  15171. this._isReady = false;
  15172. return;
  15173. }
  15174. this._isReady = true;
  15175. if (this.onReady) {
  15176. this.onReady(this);
  15177. }
  15178. };
  15179. Node.prototype.getAnimationByName = function (name) {
  15180. for (var i = 0; i < this.animations.length; i++) {
  15181. var animation = this.animations[i];
  15182. if (animation.name === name) {
  15183. return animation;
  15184. }
  15185. }
  15186. return null;
  15187. };
  15188. Node.prototype.createAnimationRange = function (name, from, to) {
  15189. // check name not already in use
  15190. if (!this._ranges[name]) {
  15191. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15192. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15193. if (this.animations[i]) {
  15194. this.animations[i].createRange(name, from, to);
  15195. }
  15196. }
  15197. }
  15198. };
  15199. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15200. if (deleteFrames === void 0) { deleteFrames = true; }
  15201. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15202. if (this.animations[i]) {
  15203. this.animations[i].deleteRange(name, deleteFrames);
  15204. }
  15205. }
  15206. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15207. };
  15208. Node.prototype.getAnimationRange = function (name) {
  15209. return this._ranges[name];
  15210. };
  15211. /**
  15212. * Will start the animation sequence
  15213. * @param name defines the range frames for animation sequence
  15214. * @param loop defines if the animation should loop (false by default)
  15215. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15216. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15217. * @returns the {BABYLON.Animatable} object created for this animation. If range does not exist, it will return null
  15218. */
  15219. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15220. var range = this.getAnimationRange(name);
  15221. if (!range) {
  15222. return null;
  15223. }
  15224. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15225. };
  15226. Node.prototype.serializeAnimationRanges = function () {
  15227. var serializationRanges = [];
  15228. for (var name in this._ranges) {
  15229. var localRange = this._ranges[name];
  15230. if (!localRange) {
  15231. continue;
  15232. }
  15233. var range = {};
  15234. range.name = name;
  15235. range.from = localRange.from;
  15236. range.to = localRange.to;
  15237. serializationRanges.push(range);
  15238. }
  15239. return serializationRanges;
  15240. };
  15241. // override it in derived class
  15242. Node.prototype.computeWorldMatrix = function (force) {
  15243. return BABYLON.Matrix.Identity();
  15244. };
  15245. Node.prototype.dispose = function () {
  15246. this.parent = null;
  15247. // Callback
  15248. this.onDisposeObservable.notifyObservers(this);
  15249. this.onDisposeObservable.clear();
  15250. // Behaviors
  15251. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15252. var behavior = _a[_i];
  15253. behavior.detach();
  15254. }
  15255. this._behaviors = [];
  15256. };
  15257. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15258. if (parsedNode.ranges) {
  15259. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15260. var data = parsedNode.ranges[index];
  15261. node.createAnimationRange(data.name, data.from, data.to);
  15262. }
  15263. }
  15264. };
  15265. __decorate([
  15266. BABYLON.serialize()
  15267. ], Node.prototype, "name", void 0);
  15268. __decorate([
  15269. BABYLON.serialize()
  15270. ], Node.prototype, "id", void 0);
  15271. __decorate([
  15272. BABYLON.serialize()
  15273. ], Node.prototype, "uniqueId", void 0);
  15274. __decorate([
  15275. BABYLON.serialize()
  15276. ], Node.prototype, "state", void 0);
  15277. __decorate([
  15278. BABYLON.serialize()
  15279. ], Node.prototype, "metadata", void 0);
  15280. return Node;
  15281. }());
  15282. BABYLON.Node = Node;
  15283. })(BABYLON || (BABYLON = {}));
  15284. //# sourceMappingURL=babylon.node.js.map
  15285. var BABYLON;
  15286. (function (BABYLON) {
  15287. var BoundingSphere = /** @class */ (function () {
  15288. function BoundingSphere(minimum, maximum) {
  15289. this.minimum = minimum;
  15290. this.maximum = maximum;
  15291. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15292. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15293. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15294. this.radius = distance * 0.5;
  15295. this.centerWorld = BABYLON.Vector3.Zero();
  15296. this._update(BABYLON.Matrix.Identity());
  15297. }
  15298. // Methods
  15299. BoundingSphere.prototype._update = function (world) {
  15300. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15301. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15302. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15303. };
  15304. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15305. for (var i = 0; i < 6; i++) {
  15306. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15307. return false;
  15308. }
  15309. return true;
  15310. };
  15311. BoundingSphere.prototype.intersectsPoint = function (point) {
  15312. var x = this.centerWorld.x - point.x;
  15313. var y = this.centerWorld.y - point.y;
  15314. var z = this.centerWorld.z - point.z;
  15315. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15316. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  15317. return false;
  15318. return true;
  15319. };
  15320. // Statics
  15321. BoundingSphere.Intersects = function (sphere0, sphere1) {
  15322. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  15323. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  15324. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  15325. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15326. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  15327. return false;
  15328. return true;
  15329. };
  15330. return BoundingSphere;
  15331. }());
  15332. BABYLON.BoundingSphere = BoundingSphere;
  15333. })(BABYLON || (BABYLON = {}));
  15334. //# sourceMappingURL=babylon.boundingSphere.js.map
  15335. var BABYLON;
  15336. (function (BABYLON) {
  15337. var BoundingBox = /** @class */ (function () {
  15338. function BoundingBox(minimum, maximum) {
  15339. this.minimum = minimum;
  15340. this.maximum = maximum;
  15341. this.vectors = new Array();
  15342. this.vectorsWorld = new Array();
  15343. // Bounding vectors
  15344. this.vectors.push(this.minimum.clone());
  15345. this.vectors.push(this.maximum.clone());
  15346. this.vectors.push(this.minimum.clone());
  15347. this.vectors[2].x = this.maximum.x;
  15348. this.vectors.push(this.minimum.clone());
  15349. this.vectors[3].y = this.maximum.y;
  15350. this.vectors.push(this.minimum.clone());
  15351. this.vectors[4].z = this.maximum.z;
  15352. this.vectors.push(this.maximum.clone());
  15353. this.vectors[5].z = this.minimum.z;
  15354. this.vectors.push(this.maximum.clone());
  15355. this.vectors[6].x = this.minimum.x;
  15356. this.vectors.push(this.maximum.clone());
  15357. this.vectors[7].y = this.minimum.y;
  15358. // OBB
  15359. this.center = this.maximum.add(this.minimum).scale(0.5);
  15360. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  15361. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  15362. // World
  15363. for (var index = 0; index < this.vectors.length; index++) {
  15364. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  15365. }
  15366. this.minimumWorld = BABYLON.Vector3.Zero();
  15367. this.maximumWorld = BABYLON.Vector3.Zero();
  15368. this.centerWorld = BABYLON.Vector3.Zero();
  15369. this.extendSizeWorld = BABYLON.Vector3.Zero();
  15370. this._update(BABYLON.Matrix.Identity());
  15371. }
  15372. // Methods
  15373. BoundingBox.prototype.getWorldMatrix = function () {
  15374. return this._worldMatrix;
  15375. };
  15376. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  15377. this._worldMatrix.copyFrom(matrix);
  15378. return this;
  15379. };
  15380. BoundingBox.prototype._update = function (world) {
  15381. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  15382. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  15383. for (var index = 0; index < this.vectors.length; index++) {
  15384. var v = this.vectorsWorld[index];
  15385. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  15386. if (v.x < this.minimumWorld.x)
  15387. this.minimumWorld.x = v.x;
  15388. if (v.y < this.minimumWorld.y)
  15389. this.minimumWorld.y = v.y;
  15390. if (v.z < this.minimumWorld.z)
  15391. this.minimumWorld.z = v.z;
  15392. if (v.x > this.maximumWorld.x)
  15393. this.maximumWorld.x = v.x;
  15394. if (v.y > this.maximumWorld.y)
  15395. this.maximumWorld.y = v.y;
  15396. if (v.z > this.maximumWorld.z)
  15397. this.maximumWorld.z = v.z;
  15398. }
  15399. // Extend
  15400. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  15401. this.extendSizeWorld.scaleInPlace(0.5);
  15402. // OBB
  15403. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  15404. this.centerWorld.scaleInPlace(0.5);
  15405. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  15406. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  15407. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  15408. this._worldMatrix = world;
  15409. };
  15410. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  15411. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  15412. };
  15413. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15414. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  15415. };
  15416. BoundingBox.prototype.intersectsPoint = function (point) {
  15417. var delta = -BABYLON.Epsilon;
  15418. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  15419. return false;
  15420. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  15421. return false;
  15422. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  15423. return false;
  15424. return true;
  15425. };
  15426. BoundingBox.prototype.intersectsSphere = function (sphere) {
  15427. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  15428. };
  15429. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  15430. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  15431. return false;
  15432. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  15433. return false;
  15434. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  15435. return false;
  15436. return true;
  15437. };
  15438. // Statics
  15439. BoundingBox.Intersects = function (box0, box1) {
  15440. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  15441. return false;
  15442. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  15443. return false;
  15444. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  15445. return false;
  15446. return true;
  15447. };
  15448. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  15449. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  15450. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  15451. return (num <= (sphereRadius * sphereRadius));
  15452. };
  15453. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  15454. for (var p = 0; p < 6; p++) {
  15455. for (var i = 0; i < 8; i++) {
  15456. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15457. return false;
  15458. }
  15459. }
  15460. }
  15461. return true;
  15462. };
  15463. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  15464. for (var p = 0; p < 6; p++) {
  15465. var inCount = 8;
  15466. for (var i = 0; i < 8; i++) {
  15467. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15468. --inCount;
  15469. }
  15470. else {
  15471. break;
  15472. }
  15473. }
  15474. if (inCount === 0)
  15475. return false;
  15476. }
  15477. return true;
  15478. };
  15479. return BoundingBox;
  15480. }());
  15481. BABYLON.BoundingBox = BoundingBox;
  15482. })(BABYLON || (BABYLON = {}));
  15483. //# sourceMappingURL=babylon.boundingBox.js.map
  15484. var BABYLON;
  15485. (function (BABYLON) {
  15486. var computeBoxExtents = function (axis, box) {
  15487. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  15488. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  15489. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  15490. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  15491. var r = r0 + r1 + r2;
  15492. return {
  15493. min: p - r,
  15494. max: p + r
  15495. };
  15496. };
  15497. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  15498. var axisOverlap = function (axis, box0, box1) {
  15499. var result0 = computeBoxExtents(axis, box0);
  15500. var result1 = computeBoxExtents(axis, box1);
  15501. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  15502. };
  15503. var BoundingInfo = /** @class */ (function () {
  15504. function BoundingInfo(minimum, maximum) {
  15505. this.minimum = minimum;
  15506. this.maximum = maximum;
  15507. this._isLocked = false;
  15508. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  15509. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  15510. }
  15511. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  15512. get: function () {
  15513. return this._isLocked;
  15514. },
  15515. set: function (value) {
  15516. this._isLocked = value;
  15517. },
  15518. enumerable: true,
  15519. configurable: true
  15520. });
  15521. // Methods
  15522. BoundingInfo.prototype.update = function (world) {
  15523. if (this._isLocked) {
  15524. return;
  15525. }
  15526. this.boundingBox._update(world);
  15527. this.boundingSphere._update(world);
  15528. };
  15529. /**
  15530. * Recreate the bounding info to be centered around a specific point given a specific extend.
  15531. * @param center New center of the bounding info
  15532. * @param extend New extend of the bounding info
  15533. */
  15534. BoundingInfo.prototype.centerOn = function (center, extend) {
  15535. this.minimum = center.subtract(extend);
  15536. this.maximum = center.add(extend);
  15537. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  15538. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  15539. return this;
  15540. };
  15541. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  15542. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  15543. return false;
  15544. return this.boundingBox.isInFrustum(frustumPlanes);
  15545. };
  15546. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  15547. /**
  15548. * Gets the world distance between the min and max points of the bounding box
  15549. */
  15550. get: function () {
  15551. var boundingBox = this.boundingBox;
  15552. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  15553. return size.length();
  15554. },
  15555. enumerable: true,
  15556. configurable: true
  15557. });
  15558. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15559. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  15560. };
  15561. BoundingInfo.prototype._checkCollision = function (collider) {
  15562. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  15563. };
  15564. BoundingInfo.prototype.intersectsPoint = function (point) {
  15565. if (!this.boundingSphere.centerWorld) {
  15566. return false;
  15567. }
  15568. if (!this.boundingSphere.intersectsPoint(point)) {
  15569. return false;
  15570. }
  15571. if (!this.boundingBox.intersectsPoint(point)) {
  15572. return false;
  15573. }
  15574. return true;
  15575. };
  15576. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  15577. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  15578. return false;
  15579. }
  15580. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  15581. return false;
  15582. }
  15583. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  15584. return false;
  15585. }
  15586. if (!precise) {
  15587. return true;
  15588. }
  15589. var box0 = this.boundingBox;
  15590. var box1 = boundingInfo.boundingBox;
  15591. if (!axisOverlap(box0.directions[0], box0, box1))
  15592. return false;
  15593. if (!axisOverlap(box0.directions[1], box0, box1))
  15594. return false;
  15595. if (!axisOverlap(box0.directions[2], box0, box1))
  15596. return false;
  15597. if (!axisOverlap(box1.directions[0], box0, box1))
  15598. return false;
  15599. if (!axisOverlap(box1.directions[1], box0, box1))
  15600. return false;
  15601. if (!axisOverlap(box1.directions[2], box0, box1))
  15602. return false;
  15603. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  15604. return false;
  15605. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  15606. return false;
  15607. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  15608. return false;
  15609. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  15610. return false;
  15611. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  15612. return false;
  15613. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  15614. return false;
  15615. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  15616. return false;
  15617. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  15618. return false;
  15619. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  15620. return false;
  15621. return true;
  15622. };
  15623. return BoundingInfo;
  15624. }());
  15625. BABYLON.BoundingInfo = BoundingInfo;
  15626. })(BABYLON || (BABYLON = {}));
  15627. //# sourceMappingURL=babylon.boundingInfo.js.map
  15628. var BABYLON;
  15629. (function (BABYLON) {
  15630. var TransformNode = /** @class */ (function (_super) {
  15631. __extends(TransformNode, _super);
  15632. function TransformNode(name, scene, isPure) {
  15633. if (scene === void 0) { scene = null; }
  15634. if (isPure === void 0) { isPure = true; }
  15635. var _this = _super.call(this, name, scene) || this;
  15636. // Properties
  15637. _this._rotation = BABYLON.Vector3.Zero();
  15638. _this._scaling = BABYLON.Vector3.One();
  15639. _this._isDirty = false;
  15640. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  15641. _this.scalingDeterminant = 1;
  15642. _this.infiniteDistance = false;
  15643. _this.position = BABYLON.Vector3.Zero();
  15644. _this._localWorld = BABYLON.Matrix.Zero();
  15645. _this._worldMatrix = BABYLON.Matrix.Zero();
  15646. _this._worldMatrixDeterminant = 0;
  15647. _this._absolutePosition = BABYLON.Vector3.Zero();
  15648. _this._pivotMatrix = BABYLON.Matrix.Identity();
  15649. _this._postMultiplyPivotMatrix = false;
  15650. _this._isWorldMatrixFrozen = false;
  15651. /**
  15652. * An event triggered after the world matrix is updated
  15653. * @type {BABYLON.Observable}
  15654. */
  15655. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  15656. _this._nonUniformScaling = false;
  15657. if (isPure) {
  15658. _this.getScene().addTransformNode(_this);
  15659. }
  15660. return _this;
  15661. }
  15662. Object.defineProperty(TransformNode.prototype, "rotation", {
  15663. /**
  15664. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  15665. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  15666. * Default : (0.0, 0.0, 0.0)
  15667. */
  15668. get: function () {
  15669. return this._rotation;
  15670. },
  15671. set: function (newRotation) {
  15672. this._rotation = newRotation;
  15673. },
  15674. enumerable: true,
  15675. configurable: true
  15676. });
  15677. Object.defineProperty(TransformNode.prototype, "scaling", {
  15678. /**
  15679. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15680. * Default : (1.0, 1.0, 1.0)
  15681. */
  15682. get: function () {
  15683. return this._scaling;
  15684. },
  15685. /**
  15686. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15687. * Default : (1.0, 1.0, 1.0)
  15688. */
  15689. set: function (newScaling) {
  15690. this._scaling = newScaling;
  15691. },
  15692. enumerable: true,
  15693. configurable: true
  15694. });
  15695. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  15696. /**
  15697. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  15698. * It's null by default.
  15699. * 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)
  15700. */
  15701. get: function () {
  15702. return this._rotationQuaternion;
  15703. },
  15704. set: function (quaternion) {
  15705. this._rotationQuaternion = quaternion;
  15706. //reset the rotation vector.
  15707. if (quaternion && this.rotation.length()) {
  15708. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  15709. }
  15710. },
  15711. enumerable: true,
  15712. configurable: true
  15713. });
  15714. /**
  15715. * Returns the latest update of the World matrix
  15716. * Returns a Matrix.
  15717. */
  15718. TransformNode.prototype.getWorldMatrix = function () {
  15719. if (this._currentRenderId !== this.getScene().getRenderId()) {
  15720. this.computeWorldMatrix();
  15721. }
  15722. return this._worldMatrix;
  15723. };
  15724. /**
  15725. * Returns the latest update of the World matrix determinant.
  15726. */
  15727. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  15728. return this._worldMatrixDeterminant;
  15729. };
  15730. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  15731. /**
  15732. * Returns directly the latest state of the mesh World matrix.
  15733. * A Matrix is returned.
  15734. */
  15735. get: function () {
  15736. return this._worldMatrix;
  15737. },
  15738. enumerable: true,
  15739. configurable: true
  15740. });
  15741. /**
  15742. * Copies the paramater passed Matrix into the mesh Pose matrix.
  15743. * Returns the AbstractMesh.
  15744. */
  15745. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  15746. this._poseMatrix.copyFrom(matrix);
  15747. return this;
  15748. };
  15749. /**
  15750. * Returns the mesh Pose matrix.
  15751. * Returned object : Matrix
  15752. */
  15753. TransformNode.prototype.getPoseMatrix = function () {
  15754. return this._poseMatrix;
  15755. };
  15756. TransformNode.prototype._isSynchronized = function () {
  15757. if (this._isDirty) {
  15758. return false;
  15759. }
  15760. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  15761. return false;
  15762. if (this._cache.pivotMatrixUpdated) {
  15763. return false;
  15764. }
  15765. if (this.infiniteDistance) {
  15766. return false;
  15767. }
  15768. if (!this._cache.position.equals(this.position))
  15769. return false;
  15770. if (this.rotationQuaternion) {
  15771. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  15772. return false;
  15773. }
  15774. if (!this._cache.rotation.equals(this.rotation))
  15775. return false;
  15776. if (!this._cache.scaling.equals(this.scaling))
  15777. return false;
  15778. return true;
  15779. };
  15780. TransformNode.prototype._initCache = function () {
  15781. _super.prototype._initCache.call(this);
  15782. this._cache.localMatrixUpdated = false;
  15783. this._cache.position = BABYLON.Vector3.Zero();
  15784. this._cache.scaling = BABYLON.Vector3.Zero();
  15785. this._cache.rotation = BABYLON.Vector3.Zero();
  15786. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  15787. this._cache.billboardMode = -1;
  15788. };
  15789. TransformNode.prototype.markAsDirty = function (property) {
  15790. if (property === "rotation") {
  15791. this.rotationQuaternion = null;
  15792. }
  15793. this._currentRenderId = Number.MAX_VALUE;
  15794. this._isDirty = true;
  15795. return this;
  15796. };
  15797. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  15798. /**
  15799. * Returns the current mesh absolute position.
  15800. * Retuns a Vector3.
  15801. */
  15802. get: function () {
  15803. return this._absolutePosition;
  15804. },
  15805. enumerable: true,
  15806. configurable: true
  15807. });
  15808. /**
  15809. * Sets a new matrix to apply before all other transformation
  15810. * @param matrix defines the transform matrix
  15811. * @returns the current TransformNode
  15812. */
  15813. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  15814. return this.setPivotMatrix(matrix, false);
  15815. };
  15816. /**
  15817. * Sets a new pivot matrix to the current node
  15818. * @param matrix defines the new pivot matrix to use
  15819. * @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
  15820. * @returns the current TransformNode
  15821. */
  15822. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  15823. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  15824. this._pivotMatrix = matrix.clone();
  15825. this._cache.pivotMatrixUpdated = true;
  15826. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  15827. if (this._postMultiplyPivotMatrix) {
  15828. if (!this._pivotMatrixInverse) {
  15829. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  15830. }
  15831. else {
  15832. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  15833. }
  15834. }
  15835. return this;
  15836. };
  15837. /**
  15838. * Returns the mesh pivot matrix.
  15839. * Default : Identity.
  15840. * A Matrix is returned.
  15841. */
  15842. TransformNode.prototype.getPivotMatrix = function () {
  15843. return this._pivotMatrix;
  15844. };
  15845. /**
  15846. * Prevents the World matrix to be computed any longer.
  15847. * Returns the AbstractMesh.
  15848. */
  15849. TransformNode.prototype.freezeWorldMatrix = function () {
  15850. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  15851. this.computeWorldMatrix(true);
  15852. this._isWorldMatrixFrozen = true;
  15853. return this;
  15854. };
  15855. /**
  15856. * Allows back the World matrix computation.
  15857. * Returns the AbstractMesh.
  15858. */
  15859. TransformNode.prototype.unfreezeWorldMatrix = function () {
  15860. this._isWorldMatrixFrozen = false;
  15861. this.computeWorldMatrix(true);
  15862. return this;
  15863. };
  15864. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  15865. /**
  15866. * True if the World matrix has been frozen.
  15867. * Returns a boolean.
  15868. */
  15869. get: function () {
  15870. return this._isWorldMatrixFrozen;
  15871. },
  15872. enumerable: true,
  15873. configurable: true
  15874. });
  15875. /**
  15876. * Retuns the mesh absolute position in the World.
  15877. * Returns a Vector3.
  15878. */
  15879. TransformNode.prototype.getAbsolutePosition = function () {
  15880. this.computeWorldMatrix();
  15881. return this._absolutePosition;
  15882. };
  15883. /**
  15884. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  15885. * Returns the AbstractMesh.
  15886. */
  15887. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  15888. if (!absolutePosition) {
  15889. return this;
  15890. }
  15891. var absolutePositionX;
  15892. var absolutePositionY;
  15893. var absolutePositionZ;
  15894. if (absolutePosition.x === undefined) {
  15895. if (arguments.length < 3) {
  15896. return this;
  15897. }
  15898. absolutePositionX = arguments[0];
  15899. absolutePositionY = arguments[1];
  15900. absolutePositionZ = arguments[2];
  15901. }
  15902. else {
  15903. absolutePositionX = absolutePosition.x;
  15904. absolutePositionY = absolutePosition.y;
  15905. absolutePositionZ = absolutePosition.z;
  15906. }
  15907. if (this.parent) {
  15908. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  15909. invertParentWorldMatrix.invert();
  15910. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  15911. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  15912. }
  15913. else {
  15914. this.position.x = absolutePositionX;
  15915. this.position.y = absolutePositionY;
  15916. this.position.z = absolutePositionZ;
  15917. }
  15918. return this;
  15919. };
  15920. /**
  15921. * Sets the mesh position in its local space.
  15922. * Returns the AbstractMesh.
  15923. */
  15924. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  15925. this.computeWorldMatrix();
  15926. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  15927. return this;
  15928. };
  15929. /**
  15930. * Returns the mesh position in the local space from the current World matrix values.
  15931. * Returns a new Vector3.
  15932. */
  15933. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  15934. this.computeWorldMatrix();
  15935. var invLocalWorldMatrix = this._localWorld.clone();
  15936. invLocalWorldMatrix.invert();
  15937. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  15938. };
  15939. /**
  15940. * Translates the mesh along the passed Vector3 in its local space.
  15941. * Returns the AbstractMesh.
  15942. */
  15943. TransformNode.prototype.locallyTranslate = function (vector3) {
  15944. this.computeWorldMatrix(true);
  15945. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  15946. return this;
  15947. };
  15948. /**
  15949. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  15950. * @param targetPoint the position (must be in same space as current mesh) to look at
  15951. * @param yawCor optional yaw (y-axis) correction in radians
  15952. * @param pitchCor optional pitch (x-axis) correction in radians
  15953. * @param rollCor optional roll (z-axis) correction in radians
  15954. * @param space the choosen space of the target
  15955. * @returns the TransformNode.
  15956. */
  15957. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  15958. if (yawCor === void 0) { yawCor = 0; }
  15959. if (pitchCor === void 0) { pitchCor = 0; }
  15960. if (rollCor === void 0) { rollCor = 0; }
  15961. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  15962. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  15963. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  15964. targetPoint.subtractToRef(pos, dv);
  15965. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  15966. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  15967. var pitch = Math.atan2(dv.y, len);
  15968. if (this.rotationQuaternion) {
  15969. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  15970. }
  15971. else {
  15972. this.rotation.x = pitch + pitchCor;
  15973. this.rotation.y = yaw + yawCor;
  15974. this.rotation.z = rollCor;
  15975. }
  15976. return this;
  15977. };
  15978. /**
  15979. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  15980. * This Vector3 is expressed in the World space.
  15981. */
  15982. TransformNode.prototype.getDirection = function (localAxis) {
  15983. var result = BABYLON.Vector3.Zero();
  15984. this.getDirectionToRef(localAxis, result);
  15985. return result;
  15986. };
  15987. /**
  15988. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  15989. * localAxis is expressed in the mesh local space.
  15990. * result is computed in the Wordl space from the mesh World matrix.
  15991. * Returns the AbstractMesh.
  15992. */
  15993. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  15994. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15995. return this;
  15996. };
  15997. /**
  15998. * Sets a new pivot point to the current node
  15999. * @param point defines the new pivot point to use
  16000. * @param space defines if the point is in world or local space (local by default)
  16001. * @returns the current TransformNode
  16002. */
  16003. TransformNode.prototype.setPivotPoint = function (point, space) {
  16004. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16005. if (this.getScene().getRenderId() == 0) {
  16006. this.computeWorldMatrix(true);
  16007. }
  16008. var wm = this.getWorldMatrix();
  16009. if (space == BABYLON.Space.WORLD) {
  16010. var tmat = BABYLON.Tmp.Matrix[0];
  16011. wm.invertToRef(tmat);
  16012. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16013. }
  16014. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16015. };
  16016. /**
  16017. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16018. */
  16019. TransformNode.prototype.getPivotPoint = function () {
  16020. var point = BABYLON.Vector3.Zero();
  16021. this.getPivotPointToRef(point);
  16022. return point;
  16023. };
  16024. /**
  16025. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16026. * Returns the AbstractMesh.
  16027. */
  16028. TransformNode.prototype.getPivotPointToRef = function (result) {
  16029. result.x = -this._pivotMatrix.m[12];
  16030. result.y = -this._pivotMatrix.m[13];
  16031. result.z = -this._pivotMatrix.m[14];
  16032. return this;
  16033. };
  16034. /**
  16035. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16036. */
  16037. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16038. var point = BABYLON.Vector3.Zero();
  16039. this.getAbsolutePivotPointToRef(point);
  16040. return point;
  16041. };
  16042. /**
  16043. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16044. * Returns the AbstractMesh.
  16045. */
  16046. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16047. result.x = this._pivotMatrix.m[12];
  16048. result.y = this._pivotMatrix.m[13];
  16049. result.z = this._pivotMatrix.m[14];
  16050. this.getPivotPointToRef(result);
  16051. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16052. return this;
  16053. };
  16054. /**
  16055. * Defines the passed node as the parent of the current node.
  16056. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16057. * Returns the TransformNode.
  16058. */
  16059. TransformNode.prototype.setParent = function (node) {
  16060. if (node === null) {
  16061. var rotation = BABYLON.Tmp.Quaternion[0];
  16062. var position = BABYLON.Tmp.Vector3[0];
  16063. var scale = BABYLON.Tmp.Vector3[1];
  16064. if (this.parent && this.parent.computeWorldMatrix) {
  16065. this.parent.computeWorldMatrix(true);
  16066. }
  16067. this.computeWorldMatrix(true);
  16068. this.getWorldMatrix().decompose(scale, rotation, position);
  16069. if (this.rotationQuaternion) {
  16070. this.rotationQuaternion.copyFrom(rotation);
  16071. }
  16072. else {
  16073. rotation.toEulerAnglesToRef(this.rotation);
  16074. }
  16075. this.scaling.x = scale.x;
  16076. this.scaling.y = scale.y;
  16077. this.scaling.z = scale.z;
  16078. this.position.x = position.x;
  16079. this.position.y = position.y;
  16080. this.position.z = position.z;
  16081. }
  16082. else {
  16083. var rotation = BABYLON.Tmp.Quaternion[0];
  16084. var position = BABYLON.Tmp.Vector3[0];
  16085. var scale = BABYLON.Tmp.Vector3[1];
  16086. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16087. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16088. this.computeWorldMatrix(true);
  16089. node.computeWorldMatrix(true);
  16090. node.getWorldMatrix().invertToRef(invParentMatrix);
  16091. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16092. diffMatrix.decompose(scale, rotation, position);
  16093. if (this.rotationQuaternion) {
  16094. this.rotationQuaternion.copyFrom(rotation);
  16095. }
  16096. else {
  16097. rotation.toEulerAnglesToRef(this.rotation);
  16098. }
  16099. this.position.x = position.x;
  16100. this.position.y = position.y;
  16101. this.position.z = position.z;
  16102. this.scaling.x = scale.x;
  16103. this.scaling.y = scale.y;
  16104. this.scaling.z = scale.z;
  16105. }
  16106. this.parent = node;
  16107. return this;
  16108. };
  16109. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16110. get: function () {
  16111. return this._nonUniformScaling;
  16112. },
  16113. enumerable: true,
  16114. configurable: true
  16115. });
  16116. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16117. if (this._nonUniformScaling === value) {
  16118. return false;
  16119. }
  16120. this._nonUniformScaling = true;
  16121. return true;
  16122. };
  16123. /**
  16124. * Attach the current TransformNode to another TransformNode associated with a bone
  16125. * @param bone Bone affecting the TransformNode
  16126. * @param affectedTransformNode TransformNode associated with the bone
  16127. */
  16128. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16129. this._transformToBoneReferal = affectedTransformNode;
  16130. this.parent = bone;
  16131. if (bone.getWorldMatrix().determinant() < 0) {
  16132. this.scalingDeterminant *= -1;
  16133. }
  16134. return this;
  16135. };
  16136. TransformNode.prototype.detachFromBone = function () {
  16137. if (!this.parent) {
  16138. return this;
  16139. }
  16140. if (this.parent.getWorldMatrix().determinant() < 0) {
  16141. this.scalingDeterminant *= -1;
  16142. }
  16143. this._transformToBoneReferal = null;
  16144. this.parent = null;
  16145. return this;
  16146. };
  16147. /**
  16148. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16149. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16150. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16151. * The passed axis is also normalized.
  16152. * Returns the AbstractMesh.
  16153. */
  16154. TransformNode.prototype.rotate = function (axis, amount, space) {
  16155. axis.normalize();
  16156. if (!this.rotationQuaternion) {
  16157. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16158. this.rotation = BABYLON.Vector3.Zero();
  16159. }
  16160. var rotationQuaternion;
  16161. if (!space || space === BABYLON.Space.LOCAL) {
  16162. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16163. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16164. }
  16165. else {
  16166. if (this.parent) {
  16167. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16168. invertParentWorldMatrix.invert();
  16169. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16170. }
  16171. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16172. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16173. }
  16174. return this;
  16175. };
  16176. /**
  16177. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16178. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16179. * The passed axis is also normalized.
  16180. * Returns the AbstractMesh.
  16181. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16182. */
  16183. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16184. axis.normalize();
  16185. if (!this.rotationQuaternion) {
  16186. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16187. this.rotation.copyFromFloats(0, 0, 0);
  16188. }
  16189. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16190. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16191. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16192. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16193. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16194. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16195. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16196. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16197. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16198. return this;
  16199. };
  16200. /**
  16201. * Translates the mesh along the axis vector for the passed distance in the given space.
  16202. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16203. * Returns the AbstractMesh.
  16204. */
  16205. TransformNode.prototype.translate = function (axis, distance, space) {
  16206. var displacementVector = axis.scale(distance);
  16207. if (!space || space === BABYLON.Space.LOCAL) {
  16208. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16209. this.setPositionWithLocalVector(tempV3);
  16210. }
  16211. else {
  16212. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16213. }
  16214. return this;
  16215. };
  16216. /**
  16217. * Adds a rotation step to the mesh current rotation.
  16218. * x, y, z are Euler angles expressed in radians.
  16219. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16220. * This means this rotation is made in the mesh local space only.
  16221. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16222. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16223. * ```javascript
  16224. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16225. * ```
  16226. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16227. * 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.
  16228. * Returns the AbstractMesh.
  16229. */
  16230. TransformNode.prototype.addRotation = function (x, y, z) {
  16231. var rotationQuaternion;
  16232. if (this.rotationQuaternion) {
  16233. rotationQuaternion = this.rotationQuaternion;
  16234. }
  16235. else {
  16236. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16237. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16238. }
  16239. var accumulation = BABYLON.Tmp.Quaternion[0];
  16240. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16241. rotationQuaternion.multiplyInPlace(accumulation);
  16242. if (!this.rotationQuaternion) {
  16243. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16244. }
  16245. return this;
  16246. };
  16247. /**
  16248. * Computes the mesh World matrix and returns it.
  16249. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16250. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16251. * If the parameter `force`is set to `true`, the actual computation is done.
  16252. * Returns the mesh World Matrix.
  16253. */
  16254. TransformNode.prototype.computeWorldMatrix = function (force) {
  16255. if (this._isWorldMatrixFrozen) {
  16256. return this._worldMatrix;
  16257. }
  16258. if (!force && this.isSynchronized(true)) {
  16259. return this._worldMatrix;
  16260. }
  16261. this._cache.position.copyFrom(this.position);
  16262. this._cache.scaling.copyFrom(this.scaling);
  16263. this._cache.pivotMatrixUpdated = false;
  16264. this._cache.billboardMode = this.billboardMode;
  16265. this._currentRenderId = this.getScene().getRenderId();
  16266. this._isDirty = false;
  16267. // Scaling
  16268. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16269. // Rotation
  16270. //rotate, if quaternion is set and rotation was used
  16271. if (this.rotationQuaternion) {
  16272. var len = this.rotation.length();
  16273. if (len) {
  16274. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16275. this.rotation.copyFromFloats(0, 0, 0);
  16276. }
  16277. }
  16278. if (this.rotationQuaternion) {
  16279. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16280. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16281. }
  16282. else {
  16283. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16284. this._cache.rotation.copyFrom(this.rotation);
  16285. }
  16286. // Translation
  16287. var camera = this.getScene().activeCamera;
  16288. if (this.infiniteDistance && !this.parent && camera) {
  16289. var cameraWorldMatrix = camera.getWorldMatrix();
  16290. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16291. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16292. }
  16293. else {
  16294. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16295. }
  16296. // Composing transformations
  16297. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16298. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16299. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16300. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16301. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16302. // Need to decompose each rotation here
  16303. var currentPosition = BABYLON.Tmp.Vector3[3];
  16304. if (this.parent && this.parent.getWorldMatrix) {
  16305. if (this._transformToBoneReferal) {
  16306. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16307. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16308. }
  16309. else {
  16310. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  16311. }
  16312. }
  16313. else {
  16314. currentPosition.copyFrom(this.position);
  16315. }
  16316. currentPosition.subtractInPlace(camera.globalPosition);
  16317. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  16318. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  16319. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  16320. }
  16321. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  16322. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  16323. }
  16324. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  16325. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  16326. }
  16327. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  16328. }
  16329. else {
  16330. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  16331. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  16332. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  16333. }
  16334. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  16335. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16336. }
  16337. // Local world
  16338. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  16339. // Parent
  16340. if (this.parent && this.parent.getWorldMatrix) {
  16341. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  16342. if (this._transformToBoneReferal) {
  16343. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16344. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  16345. }
  16346. else {
  16347. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  16348. }
  16349. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  16350. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  16351. this._worldMatrix.copyFrom(this._localWorld);
  16352. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  16353. }
  16354. else {
  16355. if (this._transformToBoneReferal) {
  16356. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16357. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  16358. }
  16359. else {
  16360. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  16361. }
  16362. }
  16363. this._markSyncedWithParent();
  16364. }
  16365. else {
  16366. this._worldMatrix.copyFrom(this._localWorld);
  16367. }
  16368. // Post multiply inverse of pivotMatrix
  16369. if (this._postMultiplyPivotMatrix) {
  16370. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  16371. }
  16372. // Normal matrix
  16373. if (this.scaling.isNonUniform) {
  16374. this._updateNonUniformScalingState(true);
  16375. }
  16376. else if (this.parent && this.parent._nonUniformScaling) {
  16377. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  16378. }
  16379. else {
  16380. this._updateNonUniformScalingState(false);
  16381. }
  16382. this._afterComputeWorldMatrix();
  16383. // Absolute position
  16384. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  16385. // Callbacks
  16386. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  16387. if (!this._poseMatrix) {
  16388. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  16389. }
  16390. // Cache the determinant
  16391. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  16392. return this._worldMatrix;
  16393. };
  16394. TransformNode.prototype._afterComputeWorldMatrix = function () {
  16395. };
  16396. /**
  16397. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  16398. * @param func: callback function to add
  16399. *
  16400. * Returns the TransformNode.
  16401. */
  16402. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  16403. this.onAfterWorldMatrixUpdateObservable.add(func);
  16404. return this;
  16405. };
  16406. /**
  16407. * Removes a registered callback function.
  16408. * Returns the TransformNode.
  16409. */
  16410. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  16411. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  16412. return this;
  16413. };
  16414. /**
  16415. * Clone the current transform node
  16416. * Returns the new transform node
  16417. * @param name Name of the new clone
  16418. * @param newParent New parent for the clone
  16419. * @param doNotCloneChildren Do not clone children hierarchy
  16420. */
  16421. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16422. var _this = this;
  16423. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  16424. result.name = name;
  16425. result.id = name;
  16426. if (newParent) {
  16427. result.parent = newParent;
  16428. }
  16429. if (!doNotCloneChildren) {
  16430. // Children
  16431. var directDescendants = this.getDescendants(true);
  16432. for (var index = 0; index < directDescendants.length; index++) {
  16433. var child = directDescendants[index];
  16434. if (child.clone) {
  16435. child.clone(name + "." + child.name, result);
  16436. }
  16437. }
  16438. }
  16439. return result;
  16440. };
  16441. TransformNode.prototype.serialize = function (currentSerializationObject) {
  16442. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  16443. serializationObject.type = this.getClassName();
  16444. // Parent
  16445. if (this.parent) {
  16446. serializationObject.parentId = this.parent.id;
  16447. }
  16448. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  16449. serializationObject.tags = BABYLON.Tags.GetTags(this);
  16450. }
  16451. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  16452. serializationObject.isEnabled = this.isEnabled();
  16453. // Parent
  16454. if (this.parent) {
  16455. serializationObject.parentId = this.parent.id;
  16456. }
  16457. return serializationObject;
  16458. };
  16459. // Statics
  16460. /**
  16461. * Returns a new TransformNode object parsed from the source provided.
  16462. * The parameter `parsedMesh` is the source.
  16463. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  16464. */
  16465. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  16466. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  16467. if (BABYLON.Tags) {
  16468. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  16469. }
  16470. if (parsedTransformNode.localMatrix) {
  16471. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  16472. }
  16473. else if (parsedTransformNode.pivotMatrix) {
  16474. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  16475. }
  16476. transformNode.setEnabled(parsedTransformNode.isEnabled);
  16477. // Parent
  16478. if (parsedTransformNode.parentId) {
  16479. transformNode._waitingParentId = parsedTransformNode.parentId;
  16480. }
  16481. return transformNode;
  16482. };
  16483. /**
  16484. * Disposes the TransformNode.
  16485. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16486. * Returns nothing.
  16487. */
  16488. TransformNode.prototype.dispose = function (doNotRecurse) {
  16489. // Animations
  16490. this.getScene().stopAnimation(this);
  16491. // Remove from scene
  16492. this.getScene().removeTransformNode(this);
  16493. if (!doNotRecurse) {
  16494. // Children
  16495. var objects = this.getDescendants(true);
  16496. for (var index = 0; index < objects.length; index++) {
  16497. objects[index].dispose();
  16498. }
  16499. }
  16500. else {
  16501. var childMeshes = this.getChildMeshes(true);
  16502. for (index = 0; index < childMeshes.length; index++) {
  16503. var child = childMeshes[index];
  16504. child.parent = null;
  16505. child.computeWorldMatrix(true);
  16506. }
  16507. }
  16508. this.onAfterWorldMatrixUpdateObservable.clear();
  16509. _super.prototype.dispose.call(this);
  16510. };
  16511. // Statics
  16512. TransformNode.BILLBOARDMODE_NONE = 0;
  16513. TransformNode.BILLBOARDMODE_X = 1;
  16514. TransformNode.BILLBOARDMODE_Y = 2;
  16515. TransformNode.BILLBOARDMODE_Z = 4;
  16516. TransformNode.BILLBOARDMODE_ALL = 7;
  16517. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  16518. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  16519. __decorate([
  16520. BABYLON.serializeAsVector3()
  16521. ], TransformNode.prototype, "_rotation", void 0);
  16522. __decorate([
  16523. BABYLON.serializeAsQuaternion()
  16524. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  16525. __decorate([
  16526. BABYLON.serializeAsVector3()
  16527. ], TransformNode.prototype, "_scaling", void 0);
  16528. __decorate([
  16529. BABYLON.serialize()
  16530. ], TransformNode.prototype, "billboardMode", void 0);
  16531. __decorate([
  16532. BABYLON.serialize()
  16533. ], TransformNode.prototype, "scalingDeterminant", void 0);
  16534. __decorate([
  16535. BABYLON.serialize()
  16536. ], TransformNode.prototype, "infiniteDistance", void 0);
  16537. __decorate([
  16538. BABYLON.serializeAsVector3()
  16539. ], TransformNode.prototype, "position", void 0);
  16540. return TransformNode;
  16541. }(BABYLON.Node));
  16542. BABYLON.TransformNode = TransformNode;
  16543. })(BABYLON || (BABYLON = {}));
  16544. //# sourceMappingURL=babylon.transformNode.js.map
  16545. var BABYLON;
  16546. (function (BABYLON) {
  16547. var AbstractMesh = /** @class */ (function (_super) {
  16548. __extends(AbstractMesh, _super);
  16549. // Constructor
  16550. function AbstractMesh(name, scene) {
  16551. if (scene === void 0) { scene = null; }
  16552. var _this = _super.call(this, name, scene, false) || this;
  16553. _this._facetNb = 0; // facet number
  16554. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  16555. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  16556. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  16557. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  16558. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  16559. _this._subDiv = {
  16560. max: 1,
  16561. X: 1,
  16562. Y: 1,
  16563. Z: 1
  16564. };
  16565. _this._facetDepthSort = false; // is the facet depth sort to be computed
  16566. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  16567. // Events
  16568. /**
  16569. * An event triggered when this mesh collides with another one
  16570. * @type {BABYLON.Observable}
  16571. */
  16572. _this.onCollideObservable = new BABYLON.Observable();
  16573. /**
  16574. * An event triggered when the collision's position changes
  16575. * @type {BABYLON.Observable}
  16576. */
  16577. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  16578. /**
  16579. * An event triggered when material is changed
  16580. * @type {BABYLON.Observable}
  16581. */
  16582. _this.onMaterialChangedObservable = new BABYLON.Observable();
  16583. // Properties
  16584. _this.definedFacingForward = true; // orientation for POV movement & rotation
  16585. /**
  16586. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  16587. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  16588. * or
  16589. * 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.
  16590. * for more info check WebGl documentations
  16591. */
  16592. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  16593. /**
  16594. * 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:
  16595. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  16596. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  16597. * 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.
  16598. */
  16599. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  16600. /**
  16601. * 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.
  16602. * The default value is -1 which means don't break the query and wait till the result.
  16603. */
  16604. _this.occlusionRetryCount = -1;
  16605. _this._occlusionInternalRetryCounter = 0;
  16606. _this._isOccluded = false;
  16607. _this._isOcclusionQueryInProgress = false;
  16608. _this._visibility = 1.0;
  16609. _this.alphaIndex = Number.MAX_VALUE;
  16610. _this.isVisible = true;
  16611. _this.isPickable = true;
  16612. _this.showBoundingBox = false;
  16613. _this.showSubMeshesBoundingBox = false;
  16614. _this.isBlocker = false;
  16615. _this.enablePointerMoveEvents = false;
  16616. _this.renderingGroupId = 0;
  16617. _this._receiveShadows = false;
  16618. _this.renderOutline = false;
  16619. _this.outlineColor = BABYLON.Color3.Red();
  16620. _this.outlineWidth = 0.02;
  16621. _this.renderOverlay = false;
  16622. _this.overlayColor = BABYLON.Color3.Red();
  16623. _this.overlayAlpha = 0.5;
  16624. _this._hasVertexAlpha = false;
  16625. _this._useVertexColors = true;
  16626. _this._computeBonesUsingShaders = true;
  16627. _this._numBoneInfluencers = 4;
  16628. _this._applyFog = true;
  16629. _this.useOctreeForRenderingSelection = true;
  16630. _this.useOctreeForPicking = true;
  16631. _this.useOctreeForCollisions = true;
  16632. _this._layerMask = 0x0FFFFFFF;
  16633. /**
  16634. * True if the mesh must be rendered in any case.
  16635. */
  16636. _this.alwaysSelectAsActiveMesh = false;
  16637. /**
  16638. * This scene's action manager
  16639. * @type {BABYLON.ActionManager}
  16640. */
  16641. _this.actionManager = null;
  16642. // Physics
  16643. _this.physicsImpostor = null;
  16644. // Collisions
  16645. _this._checkCollisions = false;
  16646. _this._collisionMask = -1;
  16647. _this._collisionGroup = -1;
  16648. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  16649. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  16650. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16651. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16652. // Edges
  16653. _this.edgesWidth = 1;
  16654. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  16655. // Cache
  16656. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  16657. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  16658. _this._isDisposed = false;
  16659. _this._renderId = 0;
  16660. _this._intersectionsInProgress = new Array();
  16661. _this._unIndexed = false;
  16662. _this._lightSources = new Array();
  16663. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  16664. if (collidedMesh === void 0) { collidedMesh = null; }
  16665. //TODO move this to the collision coordinator!
  16666. if (_this.getScene().workerCollisions)
  16667. newPosition.multiplyInPlace(_this._collider._radius);
  16668. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  16669. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  16670. _this.position.addInPlace(_this._diffPositionForCollisions);
  16671. }
  16672. if (collidedMesh) {
  16673. _this.onCollideObservable.notifyObservers(collidedMesh);
  16674. }
  16675. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  16676. };
  16677. _this.getScene().addMesh(_this);
  16678. _this._resyncLightSources();
  16679. return _this;
  16680. }
  16681. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  16682. get: function () {
  16683. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  16684. },
  16685. enumerable: true,
  16686. configurable: true
  16687. });
  16688. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  16689. get: function () {
  16690. return BABYLON.TransformNode.BILLBOARDMODE_X;
  16691. },
  16692. enumerable: true,
  16693. configurable: true
  16694. });
  16695. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  16696. get: function () {
  16697. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  16698. },
  16699. enumerable: true,
  16700. configurable: true
  16701. });
  16702. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  16703. get: function () {
  16704. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  16705. },
  16706. enumerable: true,
  16707. configurable: true
  16708. });
  16709. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  16710. get: function () {
  16711. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  16712. },
  16713. enumerable: true,
  16714. configurable: true
  16715. });
  16716. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  16717. /**
  16718. * Read-only : the number of facets in the mesh
  16719. */
  16720. get: function () {
  16721. return this._facetNb;
  16722. },
  16723. enumerable: true,
  16724. configurable: true
  16725. });
  16726. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  16727. /**
  16728. * The number (integer) of subdivisions per axis in the partioning space
  16729. */
  16730. get: function () {
  16731. return this._partitioningSubdivisions;
  16732. },
  16733. set: function (nb) {
  16734. this._partitioningSubdivisions = nb;
  16735. },
  16736. enumerable: true,
  16737. configurable: true
  16738. });
  16739. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  16740. /**
  16741. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  16742. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  16743. */
  16744. get: function () {
  16745. return this._partitioningBBoxRatio;
  16746. },
  16747. set: function (ratio) {
  16748. this._partitioningBBoxRatio = ratio;
  16749. },
  16750. enumerable: true,
  16751. configurable: true
  16752. });
  16753. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  16754. /**
  16755. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  16756. * Works only for updatable meshes.
  16757. * Doesn't work with multi-materials.
  16758. */
  16759. get: function () {
  16760. return this._facetDepthSort;
  16761. },
  16762. set: function (sort) {
  16763. this._facetDepthSort = sort;
  16764. },
  16765. enumerable: true,
  16766. configurable: true
  16767. });
  16768. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  16769. /**
  16770. * The location (Vector3) where the facet depth sort must be computed from.
  16771. * By default, the active camera position.
  16772. * Used only when facet depth sort is enabled.
  16773. */
  16774. get: function () {
  16775. return this._facetDepthSortFrom;
  16776. },
  16777. set: function (location) {
  16778. this._facetDepthSortFrom = location;
  16779. },
  16780. enumerable: true,
  16781. configurable: true
  16782. });
  16783. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  16784. /**
  16785. * Read-only boolean : is the feature facetData enabled ?
  16786. */
  16787. get: function () {
  16788. return this._facetDataEnabled;
  16789. },
  16790. enumerable: true,
  16791. configurable: true
  16792. });
  16793. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  16794. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  16795. return false;
  16796. }
  16797. this._markSubMeshesAsMiscDirty();
  16798. return true;
  16799. };
  16800. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  16801. set: function (callback) {
  16802. if (this._onCollideObserver) {
  16803. this.onCollideObservable.remove(this._onCollideObserver);
  16804. }
  16805. this._onCollideObserver = this.onCollideObservable.add(callback);
  16806. },
  16807. enumerable: true,
  16808. configurable: true
  16809. });
  16810. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  16811. set: function (callback) {
  16812. if (this._onCollisionPositionChangeObserver) {
  16813. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  16814. }
  16815. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  16816. },
  16817. enumerable: true,
  16818. configurable: true
  16819. });
  16820. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  16821. /**
  16822. * 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.
  16823. */
  16824. get: function () {
  16825. return this._isOccluded;
  16826. },
  16827. set: function (value) {
  16828. this._isOccluded = value;
  16829. },
  16830. enumerable: true,
  16831. configurable: true
  16832. });
  16833. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  16834. /**
  16835. * Flag to check the progress status of the query
  16836. */
  16837. get: function () {
  16838. return this._isOcclusionQueryInProgress;
  16839. },
  16840. enumerable: true,
  16841. configurable: true
  16842. });
  16843. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  16844. /**
  16845. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  16846. */
  16847. get: function () {
  16848. return this._visibility;
  16849. },
  16850. /**
  16851. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  16852. */
  16853. set: function (value) {
  16854. if (this._visibility === value) {
  16855. return;
  16856. }
  16857. this._visibility = value;
  16858. this._markSubMeshesAsMiscDirty();
  16859. },
  16860. enumerable: true,
  16861. configurable: true
  16862. });
  16863. Object.defineProperty(AbstractMesh.prototype, "material", {
  16864. get: function () {
  16865. return this._material;
  16866. },
  16867. set: function (value) {
  16868. if (this._material === value) {
  16869. return;
  16870. }
  16871. this._material = value;
  16872. if (this.onMaterialChangedObservable.hasObservers) {
  16873. this.onMaterialChangedObservable.notifyObservers(this);
  16874. }
  16875. if (!this.subMeshes) {
  16876. return;
  16877. }
  16878. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16879. var subMesh = _a[_i];
  16880. subMesh.setEffect(null);
  16881. }
  16882. },
  16883. enumerable: true,
  16884. configurable: true
  16885. });
  16886. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  16887. get: function () {
  16888. return this._receiveShadows;
  16889. },
  16890. set: function (value) {
  16891. if (this._receiveShadows === value) {
  16892. return;
  16893. }
  16894. this._receiveShadows = value;
  16895. this._markSubMeshesAsLightDirty();
  16896. },
  16897. enumerable: true,
  16898. configurable: true
  16899. });
  16900. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  16901. get: function () {
  16902. return this._hasVertexAlpha;
  16903. },
  16904. set: function (value) {
  16905. if (this._hasVertexAlpha === value) {
  16906. return;
  16907. }
  16908. this._hasVertexAlpha = value;
  16909. this._markSubMeshesAsAttributesDirty();
  16910. this._markSubMeshesAsMiscDirty();
  16911. },
  16912. enumerable: true,
  16913. configurable: true
  16914. });
  16915. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  16916. get: function () {
  16917. return this._useVertexColors;
  16918. },
  16919. set: function (value) {
  16920. if (this._useVertexColors === value) {
  16921. return;
  16922. }
  16923. this._useVertexColors = value;
  16924. this._markSubMeshesAsAttributesDirty();
  16925. },
  16926. enumerable: true,
  16927. configurable: true
  16928. });
  16929. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  16930. get: function () {
  16931. return this._computeBonesUsingShaders;
  16932. },
  16933. set: function (value) {
  16934. if (this._computeBonesUsingShaders === value) {
  16935. return;
  16936. }
  16937. this._computeBonesUsingShaders = value;
  16938. this._markSubMeshesAsAttributesDirty();
  16939. },
  16940. enumerable: true,
  16941. configurable: true
  16942. });
  16943. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  16944. get: function () {
  16945. return this._numBoneInfluencers;
  16946. },
  16947. set: function (value) {
  16948. if (this._numBoneInfluencers === value) {
  16949. return;
  16950. }
  16951. this._numBoneInfluencers = value;
  16952. this._markSubMeshesAsAttributesDirty();
  16953. },
  16954. enumerable: true,
  16955. configurable: true
  16956. });
  16957. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  16958. get: function () {
  16959. return this._applyFog;
  16960. },
  16961. set: function (value) {
  16962. if (this._applyFog === value) {
  16963. return;
  16964. }
  16965. this._applyFog = value;
  16966. this._markSubMeshesAsMiscDirty();
  16967. },
  16968. enumerable: true,
  16969. configurable: true
  16970. });
  16971. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  16972. get: function () {
  16973. return this._layerMask;
  16974. },
  16975. set: function (value) {
  16976. if (value === this._layerMask) {
  16977. return;
  16978. }
  16979. this._layerMask = value;
  16980. this._resyncLightSources();
  16981. },
  16982. enumerable: true,
  16983. configurable: true
  16984. });
  16985. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  16986. get: function () {
  16987. return this._collisionMask;
  16988. },
  16989. set: function (mask) {
  16990. this._collisionMask = !isNaN(mask) ? mask : -1;
  16991. },
  16992. enumerable: true,
  16993. configurable: true
  16994. });
  16995. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  16996. get: function () {
  16997. return this._collisionGroup;
  16998. },
  16999. set: function (mask) {
  17000. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17001. },
  17002. enumerable: true,
  17003. configurable: true
  17004. });
  17005. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17006. get: function () {
  17007. return null;
  17008. },
  17009. enumerable: true,
  17010. configurable: true
  17011. });
  17012. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17013. get: function () {
  17014. return this._skeleton;
  17015. },
  17016. set: function (value) {
  17017. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17018. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17019. }
  17020. if (value && value.needInitialSkinMatrix) {
  17021. value._registerMeshWithPoseMatrix(this);
  17022. }
  17023. this._skeleton = value;
  17024. if (!this._skeleton) {
  17025. this._bonesTransformMatrices = null;
  17026. }
  17027. this._markSubMeshesAsAttributesDirty();
  17028. },
  17029. enumerable: true,
  17030. configurable: true
  17031. });
  17032. /**
  17033. * Boolean : true if the mesh has been disposed.
  17034. */
  17035. AbstractMesh.prototype.isDisposed = function () {
  17036. return this._isDisposed;
  17037. };
  17038. /**
  17039. * Returns the string "AbstractMesh"
  17040. */
  17041. AbstractMesh.prototype.getClassName = function () {
  17042. return "AbstractMesh";
  17043. };
  17044. /**
  17045. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17046. */
  17047. AbstractMesh.prototype.toString = function (fullDetails) {
  17048. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17049. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17050. if (this._skeleton) {
  17051. ret += ", skeleton: " + this._skeleton.name;
  17052. }
  17053. if (fullDetails) {
  17054. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17055. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17056. }
  17057. return ret;
  17058. };
  17059. AbstractMesh.prototype._rebuild = function () {
  17060. if (this._occlusionQuery) {
  17061. this._occlusionQuery = null;
  17062. }
  17063. if (this._edgesRenderer) {
  17064. this._edgesRenderer._rebuild();
  17065. }
  17066. if (!this.subMeshes) {
  17067. return;
  17068. }
  17069. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17070. var subMesh = _a[_i];
  17071. subMesh._rebuild();
  17072. }
  17073. };
  17074. AbstractMesh.prototype._resyncLightSources = function () {
  17075. this._lightSources.length = 0;
  17076. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17077. var light = _a[_i];
  17078. if (!light.isEnabled()) {
  17079. continue;
  17080. }
  17081. if (light.canAffectMesh(this)) {
  17082. this._lightSources.push(light);
  17083. }
  17084. }
  17085. this._markSubMeshesAsLightDirty();
  17086. };
  17087. AbstractMesh.prototype._resyncLighSource = function (light) {
  17088. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17089. var index = this._lightSources.indexOf(light);
  17090. if (index === -1) {
  17091. if (!isIn) {
  17092. return;
  17093. }
  17094. this._lightSources.push(light);
  17095. }
  17096. else {
  17097. if (isIn) {
  17098. return;
  17099. }
  17100. this._lightSources.splice(index, 1);
  17101. }
  17102. this._markSubMeshesAsLightDirty();
  17103. };
  17104. AbstractMesh.prototype._removeLightSource = function (light) {
  17105. var index = this._lightSources.indexOf(light);
  17106. if (index === -1) {
  17107. return;
  17108. }
  17109. this._lightSources.splice(index, 1);
  17110. this._markSubMeshesAsLightDirty();
  17111. };
  17112. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17113. if (!this.subMeshes) {
  17114. return;
  17115. }
  17116. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17117. var subMesh = _a[_i];
  17118. if (subMesh._materialDefines) {
  17119. func(subMesh._materialDefines);
  17120. }
  17121. }
  17122. };
  17123. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17124. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17125. };
  17126. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17127. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17128. };
  17129. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17130. if (!this.subMeshes) {
  17131. return;
  17132. }
  17133. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17134. var subMesh = _a[_i];
  17135. var material = subMesh.getMaterial();
  17136. if (material) {
  17137. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17138. }
  17139. }
  17140. };
  17141. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17142. /**
  17143. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17144. * Default : (1.0, 1.0, 1.0)
  17145. */
  17146. get: function () {
  17147. return this._scaling;
  17148. },
  17149. /**
  17150. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17151. * Default : (1.0, 1.0, 1.0)
  17152. */
  17153. set: function (newScaling) {
  17154. this._scaling = newScaling;
  17155. if (this.physicsImpostor) {
  17156. this.physicsImpostor.forceUpdate();
  17157. }
  17158. },
  17159. enumerable: true,
  17160. configurable: true
  17161. });
  17162. // Methods
  17163. /**
  17164. * Disables the mesh edger rendering mode.
  17165. * Returns the AbstractMesh.
  17166. */
  17167. AbstractMesh.prototype.disableEdgesRendering = function () {
  17168. if (this._edgesRenderer) {
  17169. this._edgesRenderer.dispose();
  17170. this._edgesRenderer = null;
  17171. }
  17172. return this;
  17173. };
  17174. /**
  17175. * Enables the edge rendering mode on the mesh.
  17176. * This mode makes the mesh edges visible.
  17177. * Returns the AbstractMesh.
  17178. */
  17179. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17180. if (epsilon === void 0) { epsilon = 0.95; }
  17181. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17182. this.disableEdgesRendering();
  17183. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17184. return this;
  17185. };
  17186. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17187. /**
  17188. * Returns true if the mesh is blocked. Used by the class Mesh.
  17189. * Returns the boolean `false` by default.
  17190. */
  17191. get: function () {
  17192. return false;
  17193. },
  17194. enumerable: true,
  17195. configurable: true
  17196. });
  17197. /**
  17198. * Returns the mesh itself by default, used by the class Mesh.
  17199. * Returned type : AbstractMesh
  17200. */
  17201. AbstractMesh.prototype.getLOD = function (camera) {
  17202. return this;
  17203. };
  17204. /**
  17205. * Returns 0 by default, used by the class Mesh.
  17206. * Returns an integer.
  17207. */
  17208. AbstractMesh.prototype.getTotalVertices = function () {
  17209. return 0;
  17210. };
  17211. /**
  17212. * Returns null by default, used by the class Mesh.
  17213. * Returned type : integer array
  17214. */
  17215. AbstractMesh.prototype.getIndices = function () {
  17216. return null;
  17217. };
  17218. /**
  17219. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17220. * Returned type : float array or Float32Array
  17221. */
  17222. AbstractMesh.prototype.getVerticesData = function (kind) {
  17223. return null;
  17224. };
  17225. /**
  17226. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17227. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17228. * The `data` are either a numeric array either a Float32Array.
  17229. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17230. * 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).
  17231. * Note that a new underlying VertexBuffer object is created each call.
  17232. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17233. *
  17234. * Possible `kind` values :
  17235. * - BABYLON.VertexBuffer.PositionKind
  17236. * - BABYLON.VertexBuffer.UVKind
  17237. * - BABYLON.VertexBuffer.UV2Kind
  17238. * - BABYLON.VertexBuffer.UV3Kind
  17239. * - BABYLON.VertexBuffer.UV4Kind
  17240. * - BABYLON.VertexBuffer.UV5Kind
  17241. * - BABYLON.VertexBuffer.UV6Kind
  17242. * - BABYLON.VertexBuffer.ColorKind
  17243. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17244. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17245. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17246. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17247. *
  17248. * Returns the Mesh.
  17249. */
  17250. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17251. return this;
  17252. };
  17253. /**
  17254. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17255. * If the mesh has no geometry, it is simply returned as it is.
  17256. * The `data` are either a numeric array either a Float32Array.
  17257. * No new underlying VertexBuffer object is created.
  17258. * 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.
  17259. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17260. *
  17261. * Possible `kind` values :
  17262. * - BABYLON.VertexBuffer.PositionKind
  17263. * - BABYLON.VertexBuffer.UVKind
  17264. * - BABYLON.VertexBuffer.UV2Kind
  17265. * - BABYLON.VertexBuffer.UV3Kind
  17266. * - BABYLON.VertexBuffer.UV4Kind
  17267. * - BABYLON.VertexBuffer.UV5Kind
  17268. * - BABYLON.VertexBuffer.UV6Kind
  17269. * - BABYLON.VertexBuffer.ColorKind
  17270. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17271. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17272. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17273. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17274. *
  17275. * Returns the Mesh.
  17276. */
  17277. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17278. return this;
  17279. };
  17280. /**
  17281. * Sets the mesh indices.
  17282. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17283. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17284. * This method creates a new index buffer each call.
  17285. * Returns the Mesh.
  17286. */
  17287. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17288. return this;
  17289. };
  17290. /** Returns false by default, used by the class Mesh.
  17291. * Returns a boolean
  17292. */
  17293. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17294. return false;
  17295. };
  17296. /**
  17297. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17298. * Returns a BoundingInfo
  17299. */
  17300. AbstractMesh.prototype.getBoundingInfo = function () {
  17301. if (this._masterMesh) {
  17302. return this._masterMesh.getBoundingInfo();
  17303. }
  17304. if (!this._boundingInfo) {
  17305. // this._boundingInfo is being created here
  17306. this._updateBoundingInfo();
  17307. }
  17308. // cannot be null.
  17309. return this._boundingInfo;
  17310. };
  17311. /**
  17312. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17313. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17314. */
  17315. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17316. if (includeDescendants === void 0) { includeDescendants = true; }
  17317. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17318. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17319. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  17320. if (maxDimension === 0) {
  17321. return this;
  17322. }
  17323. var scale = 1 / maxDimension;
  17324. this.scaling.scaleInPlace(scale);
  17325. return this;
  17326. };
  17327. /**
  17328. * Sets a mesh new object BoundingInfo.
  17329. * Returns the AbstractMesh.
  17330. */
  17331. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  17332. this._boundingInfo = boundingInfo;
  17333. return this;
  17334. };
  17335. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  17336. get: function () {
  17337. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  17338. },
  17339. enumerable: true,
  17340. configurable: true
  17341. });
  17342. AbstractMesh.prototype._preActivate = function () {
  17343. };
  17344. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17345. };
  17346. AbstractMesh.prototype._activate = function (renderId) {
  17347. this._renderId = renderId;
  17348. };
  17349. /**
  17350. * Returns the latest update of the World matrix
  17351. * Returns a Matrix.
  17352. */
  17353. AbstractMesh.prototype.getWorldMatrix = function () {
  17354. if (this._masterMesh) {
  17355. return this._masterMesh.getWorldMatrix();
  17356. }
  17357. return _super.prototype.getWorldMatrix.call(this);
  17358. };
  17359. /**
  17360. * Returns the latest update of the World matrix determinant.
  17361. */
  17362. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  17363. if (this._masterMesh) {
  17364. return this._masterMesh._getWorldMatrixDeterminant();
  17365. }
  17366. return _super.prototype._getWorldMatrixDeterminant.call(this);
  17367. };
  17368. // ================================== Point of View Movement =================================
  17369. /**
  17370. * Perform relative position change from the point of view of behind the front of the mesh.
  17371. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17372. * Supports definition of mesh facing forward or backward.
  17373. * @param {number} amountRight
  17374. * @param {number} amountUp
  17375. * @param {number} amountForward
  17376. *
  17377. * Returns the AbstractMesh.
  17378. */
  17379. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  17380. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  17381. return this;
  17382. };
  17383. /**
  17384. * Calculate relative position change from the point of view of behind the front of the mesh.
  17385. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17386. * Supports definition of mesh facing forward or backward.
  17387. * @param {number} amountRight
  17388. * @param {number} amountUp
  17389. * @param {number} amountForward
  17390. *
  17391. * Returns a new Vector3.
  17392. */
  17393. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  17394. var rotMatrix = new BABYLON.Matrix();
  17395. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17396. rotQuaternion.toRotationMatrix(rotMatrix);
  17397. var translationDelta = BABYLON.Vector3.Zero();
  17398. var defForwardMult = this.definedFacingForward ? -1 : 1;
  17399. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  17400. return translationDelta;
  17401. };
  17402. // ================================== Point of View Rotation =================================
  17403. /**
  17404. * Perform relative rotation change from the point of view of behind the front of the mesh.
  17405. * Supports definition of mesh facing forward or backward.
  17406. * @param {number} flipBack
  17407. * @param {number} twirlClockwise
  17408. * @param {number} tiltRight
  17409. *
  17410. * Returns the AbstractMesh.
  17411. */
  17412. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17413. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  17414. return this;
  17415. };
  17416. /**
  17417. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  17418. * Supports definition of mesh facing forward or backward.
  17419. * @param {number} flipBack
  17420. * @param {number} twirlClockwise
  17421. * @param {number} tiltRight
  17422. *
  17423. * Returns a new Vector3.
  17424. */
  17425. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17426. var defForwardMult = this.definedFacingForward ? 1 : -1;
  17427. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  17428. };
  17429. /**
  17430. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  17431. * @param includeDescendants Include bounding info from descendants as well (true by default).
  17432. */
  17433. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  17434. if (includeDescendants === void 0) { includeDescendants = true; }
  17435. this.computeWorldMatrix(true);
  17436. var min;
  17437. var max;
  17438. var boundingInfo = this.getBoundingInfo();
  17439. if (!this.subMeshes) {
  17440. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17441. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17442. }
  17443. else {
  17444. min = boundingInfo.boundingBox.minimumWorld;
  17445. max = boundingInfo.boundingBox.maximumWorld;
  17446. }
  17447. if (includeDescendants) {
  17448. var descendants = this.getDescendants(false);
  17449. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  17450. var descendant = descendants_1[_i];
  17451. var childMesh = descendant;
  17452. childMesh.computeWorldMatrix(true);
  17453. //make sure we have the needed params to get mix and max
  17454. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  17455. continue;
  17456. }
  17457. var childBoundingInfo = childMesh.getBoundingInfo();
  17458. var boundingBox = childBoundingInfo.boundingBox;
  17459. var minBox = boundingBox.minimumWorld;
  17460. var maxBox = boundingBox.maximumWorld;
  17461. BABYLON.Tools.CheckExtends(minBox, min, max);
  17462. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17463. }
  17464. }
  17465. return {
  17466. min: min,
  17467. max: max
  17468. };
  17469. };
  17470. /**
  17471. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  17472. * Returns the AbstractMesh.
  17473. */
  17474. AbstractMesh.prototype._updateBoundingInfo = function () {
  17475. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  17476. this._boundingInfo.update(this.worldMatrixFromCache);
  17477. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  17478. return this;
  17479. };
  17480. /**
  17481. * Update a mesh's children BoundingInfo objects only.
  17482. * Returns the AbstractMesh.
  17483. */
  17484. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  17485. if (!this.subMeshes) {
  17486. return this;
  17487. }
  17488. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  17489. var subMesh = this.subMeshes[subIndex];
  17490. if (!subMesh.IsGlobal) {
  17491. subMesh.updateBoundingInfo(matrix);
  17492. }
  17493. }
  17494. return this;
  17495. };
  17496. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  17497. // Bounding info
  17498. this._updateBoundingInfo();
  17499. };
  17500. /**
  17501. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  17502. * A mesh is in the frustum if its bounding box intersects the frustum.
  17503. * Boolean returned.
  17504. */
  17505. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  17506. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  17507. };
  17508. /**
  17509. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  17510. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  17511. * Boolean returned.
  17512. */
  17513. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17514. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  17515. ;
  17516. };
  17517. /**
  17518. * True if the mesh intersects another mesh or a SolidParticle object.
  17519. * 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)
  17520. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  17521. * Returns a boolean.
  17522. */
  17523. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  17524. if (precise === void 0) { precise = false; }
  17525. if (!this._boundingInfo || !mesh._boundingInfo) {
  17526. return false;
  17527. }
  17528. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  17529. return true;
  17530. }
  17531. if (includeDescendants) {
  17532. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  17533. var child = _a[_i];
  17534. if (child.intersectsMesh(mesh, precise, true)) {
  17535. return true;
  17536. }
  17537. }
  17538. }
  17539. return false;
  17540. };
  17541. /**
  17542. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  17543. * Returns a boolean.
  17544. */
  17545. AbstractMesh.prototype.intersectsPoint = function (point) {
  17546. if (!this._boundingInfo) {
  17547. return false;
  17548. }
  17549. return this._boundingInfo.intersectsPoint(point);
  17550. };
  17551. AbstractMesh.prototype.getPhysicsImpostor = function () {
  17552. return this.physicsImpostor;
  17553. };
  17554. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  17555. if (camera === void 0) { camera = null; }
  17556. if (!camera) {
  17557. camera = this.getScene().activeCamera;
  17558. }
  17559. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  17560. };
  17561. /**
  17562. * Returns the distance from the mesh to the active camera.
  17563. * Returns a float.
  17564. */
  17565. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  17566. if (camera === void 0) { camera = null; }
  17567. if (!camera) {
  17568. camera = this.getScene().activeCamera;
  17569. }
  17570. return this.absolutePosition.subtract(camera.position).length();
  17571. };
  17572. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  17573. if (!this.physicsImpostor) {
  17574. return this;
  17575. }
  17576. this.physicsImpostor.applyImpulse(force, contactPoint);
  17577. return this;
  17578. };
  17579. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  17580. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  17581. return this;
  17582. }
  17583. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  17584. mainPivot: pivot1,
  17585. connectedPivot: pivot2,
  17586. nativeParams: options
  17587. });
  17588. return this;
  17589. };
  17590. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  17591. // Collisions
  17592. /**
  17593. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  17594. * Default `false`.
  17595. */
  17596. get: function () {
  17597. return this._checkCollisions;
  17598. },
  17599. set: function (collisionEnabled) {
  17600. this._checkCollisions = collisionEnabled;
  17601. if (this.getScene().workerCollisions) {
  17602. this.getScene().collisionCoordinator.onMeshUpdated(this);
  17603. }
  17604. },
  17605. enumerable: true,
  17606. configurable: true
  17607. });
  17608. Object.defineProperty(AbstractMesh.prototype, "collider", {
  17609. /**
  17610. * Gets Collider object used to compute collisions (not physics)
  17611. */
  17612. get: function () {
  17613. return this._collider;
  17614. },
  17615. enumerable: true,
  17616. configurable: true
  17617. });
  17618. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  17619. var globalPosition = this.getAbsolutePosition();
  17620. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  17621. if (!this._collider) {
  17622. this._collider = new BABYLON.Collider();
  17623. }
  17624. this._collider._radius = this.ellipsoid;
  17625. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  17626. return this;
  17627. };
  17628. // Submeshes octree
  17629. /**
  17630. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  17631. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  17632. * Returns an Octree of submeshes.
  17633. */
  17634. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  17635. if (maxCapacity === void 0) { maxCapacity = 64; }
  17636. if (maxDepth === void 0) { maxDepth = 2; }
  17637. if (!this._submeshesOctree) {
  17638. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  17639. }
  17640. this.computeWorldMatrix(true);
  17641. var boundingInfo = this.getBoundingInfo();
  17642. // Update octree
  17643. var bbox = boundingInfo.boundingBox;
  17644. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  17645. return this._submeshesOctree;
  17646. };
  17647. // Collisions
  17648. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  17649. this._generatePointsArray();
  17650. if (!this._positions) {
  17651. return this;
  17652. }
  17653. // Transformation
  17654. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  17655. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  17656. subMesh._lastColliderWorldVertices = [];
  17657. subMesh._trianglePlanes = [];
  17658. var start = subMesh.verticesStart;
  17659. var end = (subMesh.verticesStart + subMesh.verticesCount);
  17660. for (var i = start; i < end; i++) {
  17661. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  17662. }
  17663. }
  17664. // Collide
  17665. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  17666. if (collider.collisionFound) {
  17667. collider.collidedMesh = this;
  17668. }
  17669. return this;
  17670. };
  17671. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  17672. var subMeshes;
  17673. var len;
  17674. // Octrees
  17675. if (this._submeshesOctree && this.useOctreeForCollisions) {
  17676. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  17677. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  17678. len = intersections.length;
  17679. subMeshes = intersections.data;
  17680. }
  17681. else {
  17682. subMeshes = this.subMeshes;
  17683. len = subMeshes.length;
  17684. }
  17685. for (var index = 0; index < len; index++) {
  17686. var subMesh = subMeshes[index];
  17687. // Bounding test
  17688. if (len > 1 && !subMesh._checkCollision(collider))
  17689. continue;
  17690. this._collideForSubMesh(subMesh, transformMatrix, collider);
  17691. }
  17692. return this;
  17693. };
  17694. AbstractMesh.prototype._checkCollision = function (collider) {
  17695. // Bounding box test
  17696. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  17697. return this;
  17698. // Transformation matrix
  17699. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  17700. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  17701. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  17702. return this;
  17703. };
  17704. // Picking
  17705. AbstractMesh.prototype._generatePointsArray = function () {
  17706. return false;
  17707. };
  17708. /**
  17709. * Checks if the passed Ray intersects with the mesh.
  17710. * Returns an object PickingInfo.
  17711. */
  17712. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  17713. var pickingInfo = new BABYLON.PickingInfo();
  17714. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  17715. return pickingInfo;
  17716. }
  17717. if (!this._generatePointsArray()) {
  17718. return pickingInfo;
  17719. }
  17720. var intersectInfo = null;
  17721. // Octrees
  17722. var subMeshes;
  17723. var len;
  17724. if (this._submeshesOctree && this.useOctreeForPicking) {
  17725. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  17726. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  17727. len = intersections.length;
  17728. subMeshes = intersections.data;
  17729. }
  17730. else {
  17731. subMeshes = this.subMeshes;
  17732. len = subMeshes.length;
  17733. }
  17734. for (var index = 0; index < len; index++) {
  17735. var subMesh = subMeshes[index];
  17736. // Bounding test
  17737. if (len > 1 && !subMesh.canIntersects(ray))
  17738. continue;
  17739. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  17740. if (currentIntersectInfo) {
  17741. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  17742. intersectInfo = currentIntersectInfo;
  17743. intersectInfo.subMeshId = index;
  17744. if (fastCheck) {
  17745. break;
  17746. }
  17747. }
  17748. }
  17749. }
  17750. if (intersectInfo) {
  17751. // Get picked point
  17752. var world = this.getWorldMatrix();
  17753. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  17754. var direction = ray.direction.clone();
  17755. direction = direction.scale(intersectInfo.distance);
  17756. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  17757. var pickedPoint = worldOrigin.add(worldDirection);
  17758. // Return result
  17759. pickingInfo.hit = true;
  17760. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  17761. pickingInfo.pickedPoint = pickedPoint;
  17762. pickingInfo.pickedMesh = this;
  17763. pickingInfo.bu = intersectInfo.bu || 0;
  17764. pickingInfo.bv = intersectInfo.bv || 0;
  17765. pickingInfo.faceId = intersectInfo.faceId;
  17766. pickingInfo.subMeshId = intersectInfo.subMeshId;
  17767. return pickingInfo;
  17768. }
  17769. return pickingInfo;
  17770. };
  17771. /**
  17772. * Clones the mesh, used by the class Mesh.
  17773. * Just returns `null` for an AbstractMesh.
  17774. */
  17775. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17776. return null;
  17777. };
  17778. /**
  17779. * Disposes all the mesh submeshes.
  17780. * Returns the AbstractMesh.
  17781. */
  17782. AbstractMesh.prototype.releaseSubMeshes = function () {
  17783. if (this.subMeshes) {
  17784. while (this.subMeshes.length) {
  17785. this.subMeshes[0].dispose();
  17786. }
  17787. }
  17788. else {
  17789. this.subMeshes = new Array();
  17790. }
  17791. return this;
  17792. };
  17793. /**
  17794. * Disposes the AbstractMesh.
  17795. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  17796. * Returns nothing.
  17797. */
  17798. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17799. var _this = this;
  17800. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17801. var index;
  17802. // Action manager
  17803. if (this.actionManager !== undefined && this.actionManager !== null) {
  17804. this.actionManager.dispose();
  17805. this.actionManager = null;
  17806. }
  17807. // Skeleton
  17808. this.skeleton = null;
  17809. // Physics
  17810. if (this.physicsImpostor) {
  17811. this.physicsImpostor.dispose();
  17812. }
  17813. // Intersections in progress
  17814. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  17815. var other = this._intersectionsInProgress[index];
  17816. var pos = other._intersectionsInProgress.indexOf(this);
  17817. other._intersectionsInProgress.splice(pos, 1);
  17818. }
  17819. this._intersectionsInProgress = [];
  17820. // Lights
  17821. var lights = this.getScene().lights;
  17822. lights.forEach(function (light) {
  17823. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  17824. if (meshIndex !== -1) {
  17825. light.includedOnlyMeshes.splice(meshIndex, 1);
  17826. }
  17827. meshIndex = light.excludedMeshes.indexOf(_this);
  17828. if (meshIndex !== -1) {
  17829. light.excludedMeshes.splice(meshIndex, 1);
  17830. }
  17831. // Shadow generators
  17832. var generator = light.getShadowGenerator();
  17833. if (generator) {
  17834. var shadowMap = generator.getShadowMap();
  17835. if (shadowMap && shadowMap.renderList) {
  17836. meshIndex = shadowMap.renderList.indexOf(_this);
  17837. if (meshIndex !== -1) {
  17838. shadowMap.renderList.splice(meshIndex, 1);
  17839. }
  17840. }
  17841. }
  17842. });
  17843. // Edges
  17844. if (this._edgesRenderer) {
  17845. this._edgesRenderer.dispose();
  17846. this._edgesRenderer = null;
  17847. }
  17848. // SubMeshes
  17849. if (this.getClassName() !== "InstancedMesh") {
  17850. this.releaseSubMeshes();
  17851. }
  17852. // Octree
  17853. var sceneOctree = this.getScene().selectionOctree;
  17854. if (sceneOctree !== undefined && sceneOctree !== null) {
  17855. var index = sceneOctree.dynamicContent.indexOf(this);
  17856. if (index !== -1) {
  17857. sceneOctree.dynamicContent.splice(index, 1);
  17858. }
  17859. }
  17860. // Query
  17861. var engine = this.getScene().getEngine();
  17862. if (this._occlusionQuery) {
  17863. this._isOcclusionQueryInProgress = false;
  17864. engine.deleteQuery(this._occlusionQuery);
  17865. this._occlusionQuery = null;
  17866. }
  17867. // Engine
  17868. engine.wipeCaches();
  17869. // Remove from scene
  17870. this.getScene().removeMesh(this);
  17871. if (disposeMaterialAndTextures) {
  17872. if (this.material) {
  17873. this.material.dispose(false, true);
  17874. }
  17875. }
  17876. if (!doNotRecurse) {
  17877. // Particles
  17878. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  17879. if (this.getScene().particleSystems[index].emitter === this) {
  17880. this.getScene().particleSystems[index].dispose();
  17881. index--;
  17882. }
  17883. }
  17884. }
  17885. // facet data
  17886. if (this._facetDataEnabled) {
  17887. this.disableFacetData();
  17888. }
  17889. this.onAfterWorldMatrixUpdateObservable.clear();
  17890. this.onCollideObservable.clear();
  17891. this.onCollisionPositionChangeObservable.clear();
  17892. this._isDisposed = true;
  17893. _super.prototype.dispose.call(this, doNotRecurse);
  17894. };
  17895. /**
  17896. * Adds the passed mesh as a child to the current mesh.
  17897. * Returns the AbstractMesh.
  17898. */
  17899. AbstractMesh.prototype.addChild = function (mesh) {
  17900. mesh.setParent(this);
  17901. return this;
  17902. };
  17903. /**
  17904. * Removes the passed mesh from the current mesh children list.
  17905. * Returns the AbstractMesh.
  17906. */
  17907. AbstractMesh.prototype.removeChild = function (mesh) {
  17908. mesh.setParent(null);
  17909. return this;
  17910. };
  17911. // Facet data
  17912. /**
  17913. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  17914. * Returns the AbstractMesh.
  17915. */
  17916. AbstractMesh.prototype._initFacetData = function () {
  17917. if (!this._facetNormals) {
  17918. this._facetNormals = new Array();
  17919. }
  17920. if (!this._facetPositions) {
  17921. this._facetPositions = new Array();
  17922. }
  17923. if (!this._facetPartitioning) {
  17924. this._facetPartitioning = new Array();
  17925. }
  17926. this._facetNb = (this.getIndices().length / 3) | 0;
  17927. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  17928. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  17929. for (var f = 0; f < this._facetNb; f++) {
  17930. this._facetNormals[f] = BABYLON.Vector3.Zero();
  17931. this._facetPositions[f] = BABYLON.Vector3.Zero();
  17932. }
  17933. this._facetDataEnabled = true;
  17934. return this;
  17935. };
  17936. /**
  17937. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  17938. * This method can be called within the render loop.
  17939. * 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.
  17940. * Returns the AbstractMesh.
  17941. */
  17942. AbstractMesh.prototype.updateFacetData = function () {
  17943. if (!this._facetDataEnabled) {
  17944. this._initFacetData();
  17945. }
  17946. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17947. var indices = this.getIndices();
  17948. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17949. var bInfo = this.getBoundingInfo();
  17950. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  17951. // init arrays, matrix and sort function on first call
  17952. this._facetDepthSortEnabled = true;
  17953. if (indices instanceof Uint16Array) {
  17954. this._depthSortedIndices = new Uint16Array(indices);
  17955. }
  17956. else if (indices instanceof Uint32Array) {
  17957. this._depthSortedIndices = new Uint32Array(indices);
  17958. }
  17959. else {
  17960. var needs32bits = false;
  17961. for (var i = 0; i < indices.length; i++) {
  17962. if (indices[i] > 65535) {
  17963. needs32bits = true;
  17964. break;
  17965. }
  17966. }
  17967. if (needs32bits) {
  17968. this._depthSortedIndices = new Uint32Array(indices);
  17969. }
  17970. else {
  17971. this._depthSortedIndices = new Uint16Array(indices);
  17972. }
  17973. }
  17974. this._facetDepthSortFunction = function (f1, f2) {
  17975. return (f2.sqDistance - f1.sqDistance);
  17976. };
  17977. if (!this._facetDepthSortFrom) {
  17978. var camera = this.getScene().activeCamera;
  17979. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  17980. }
  17981. this._depthSortedFacets = [];
  17982. for (var f = 0; f < this._facetNb; f++) {
  17983. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  17984. this._depthSortedFacets.push(depthSortedFacet);
  17985. }
  17986. this._invertedMatrix = BABYLON.Matrix.Identity();
  17987. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  17988. }
  17989. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  17990. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  17991. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  17992. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  17993. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  17994. this._subDiv.max = this._partitioningSubdivisions;
  17995. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  17996. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  17997. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  17998. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  17999. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18000. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18001. // set the parameters for ComputeNormals()
  18002. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18003. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18004. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18005. this._facetParameters.bInfo = bInfo;
  18006. this._facetParameters.bbSize = this._bbSize;
  18007. this._facetParameters.subDiv = this._subDiv;
  18008. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18009. this._facetParameters.depthSort = this._facetDepthSort;
  18010. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18011. this.computeWorldMatrix(true);
  18012. this._worldMatrix.invertToRef(this._invertedMatrix);
  18013. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18014. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18015. }
  18016. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18017. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18018. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18019. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18020. var l = (this._depthSortedIndices.length / 3) | 0;
  18021. for (var f = 0; f < l; f++) {
  18022. var sind = this._depthSortedFacets[f].ind;
  18023. this._depthSortedIndices[f * 3] = indices[sind];
  18024. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18025. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18026. }
  18027. this.updateIndices(this._depthSortedIndices);
  18028. }
  18029. return this;
  18030. };
  18031. /**
  18032. * Returns the facetLocalNormals array.
  18033. * The normals are expressed in the mesh local space.
  18034. */
  18035. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18036. if (!this._facetNormals) {
  18037. this.updateFacetData();
  18038. }
  18039. return this._facetNormals;
  18040. };
  18041. /**
  18042. * Returns the facetLocalPositions array.
  18043. * The facet positions are expressed in the mesh local space.
  18044. */
  18045. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18046. if (!this._facetPositions) {
  18047. this.updateFacetData();
  18048. }
  18049. return this._facetPositions;
  18050. };
  18051. /**
  18052. * Returns the facetLocalPartioning array.
  18053. */
  18054. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18055. if (!this._facetPartitioning) {
  18056. this.updateFacetData();
  18057. }
  18058. return this._facetPartitioning;
  18059. };
  18060. /**
  18061. * Returns the i-th facet position in the world system.
  18062. * This method allocates a new Vector3 per call.
  18063. */
  18064. AbstractMesh.prototype.getFacetPosition = function (i) {
  18065. var pos = BABYLON.Vector3.Zero();
  18066. this.getFacetPositionToRef(i, pos);
  18067. return pos;
  18068. };
  18069. /**
  18070. * Sets the reference Vector3 with the i-th facet position in the world system.
  18071. * Returns the AbstractMesh.
  18072. */
  18073. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18074. var localPos = (this.getFacetLocalPositions())[i];
  18075. var world = this.getWorldMatrix();
  18076. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18077. return this;
  18078. };
  18079. /**
  18080. * Returns the i-th facet normal in the world system.
  18081. * This method allocates a new Vector3 per call.
  18082. */
  18083. AbstractMesh.prototype.getFacetNormal = function (i) {
  18084. var norm = BABYLON.Vector3.Zero();
  18085. this.getFacetNormalToRef(i, norm);
  18086. return norm;
  18087. };
  18088. /**
  18089. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18090. * Returns the AbstractMesh.
  18091. */
  18092. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18093. var localNorm = (this.getFacetLocalNormals())[i];
  18094. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18095. return this;
  18096. };
  18097. /**
  18098. * 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).
  18099. */
  18100. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18101. var bInfo = this.getBoundingInfo();
  18102. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18103. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18104. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18105. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18106. return null;
  18107. }
  18108. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18109. };
  18110. /**
  18111. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18112. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18113. * 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.
  18114. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18115. * 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.
  18116. */
  18117. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18118. if (checkFace === void 0) { checkFace = false; }
  18119. if (facing === void 0) { facing = true; }
  18120. var world = this.getWorldMatrix();
  18121. var invMat = BABYLON.Tmp.Matrix[5];
  18122. world.invertToRef(invMat);
  18123. var invVect = BABYLON.Tmp.Vector3[8];
  18124. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18125. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18126. if (projected) {
  18127. // tranform the local computed projected vector to world coordinates
  18128. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18129. }
  18130. return closest;
  18131. };
  18132. /**
  18133. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18134. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18135. * 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.
  18136. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18137. * 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.
  18138. */
  18139. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18140. if (checkFace === void 0) { checkFace = false; }
  18141. if (facing === void 0) { facing = true; }
  18142. var closest = null;
  18143. var tmpx = 0.0;
  18144. var tmpy = 0.0;
  18145. var tmpz = 0.0;
  18146. var d = 0.0; // tmp dot facet normal * facet position
  18147. var t0 = 0.0;
  18148. var projx = 0.0;
  18149. var projy = 0.0;
  18150. var projz = 0.0;
  18151. // Get all the facets in the same partitioning block than (x, y, z)
  18152. var facetPositions = this.getFacetLocalPositions();
  18153. var facetNormals = this.getFacetLocalNormals();
  18154. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18155. if (!facetsInBlock) {
  18156. return null;
  18157. }
  18158. // Get the closest facet to (x, y, z)
  18159. var shortest = Number.MAX_VALUE; // init distance vars
  18160. var tmpDistance = shortest;
  18161. var fib; // current facet in the block
  18162. var norm; // current facet normal
  18163. var p0; // current facet barycenter position
  18164. // loop on all the facets in the current partitioning block
  18165. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18166. fib = facetsInBlock[idx];
  18167. norm = facetNormals[fib];
  18168. p0 = facetPositions[fib];
  18169. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18170. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18171. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18172. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18173. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18174. projx = x + norm.x * t0;
  18175. projy = y + norm.y * t0;
  18176. projz = z + norm.z * t0;
  18177. tmpx = projx - x;
  18178. tmpy = projy - y;
  18179. tmpz = projz - z;
  18180. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18181. if (tmpDistance < shortest) {
  18182. shortest = tmpDistance;
  18183. closest = fib;
  18184. if (projected) {
  18185. projected.x = projx;
  18186. projected.y = projy;
  18187. projected.z = projz;
  18188. }
  18189. }
  18190. }
  18191. }
  18192. return closest;
  18193. };
  18194. /**
  18195. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18196. */
  18197. AbstractMesh.prototype.getFacetDataParameters = function () {
  18198. return this._facetParameters;
  18199. };
  18200. /**
  18201. * Disables the feature FacetData and frees the related memory.
  18202. * Returns the AbstractMesh.
  18203. */
  18204. AbstractMesh.prototype.disableFacetData = function () {
  18205. if (this._facetDataEnabled) {
  18206. this._facetDataEnabled = false;
  18207. this._facetPositions = new Array();
  18208. this._facetNormals = new Array();
  18209. this._facetPartitioning = new Array();
  18210. this._facetParameters = null;
  18211. this._depthSortedIndices = new Uint32Array(0);
  18212. }
  18213. return this;
  18214. };
  18215. /**
  18216. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18217. * Returns the mesh.
  18218. */
  18219. AbstractMesh.prototype.updateIndices = function (indices) {
  18220. return this;
  18221. };
  18222. /**
  18223. * The mesh Geometry. Actually used by the Mesh object.
  18224. * Returns a blank geometry object.
  18225. */
  18226. /**
  18227. * Creates new normals data for the mesh.
  18228. * @param updatable.
  18229. */
  18230. AbstractMesh.prototype.createNormals = function (updatable) {
  18231. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18232. var indices = this.getIndices();
  18233. var normals;
  18234. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18235. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18236. }
  18237. else {
  18238. normals = [];
  18239. }
  18240. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18241. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18242. };
  18243. /**
  18244. * Align the mesh with a normal.
  18245. * Returns the mesh.
  18246. */
  18247. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18248. if (!upDirection) {
  18249. upDirection = BABYLON.Axis.Y;
  18250. }
  18251. var axisX = BABYLON.Tmp.Vector3[0];
  18252. var axisZ = BABYLON.Tmp.Vector3[1];
  18253. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18254. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18255. if (this.rotationQuaternion) {
  18256. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18257. }
  18258. else {
  18259. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18260. }
  18261. return this;
  18262. };
  18263. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18264. var engine = this.getEngine();
  18265. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18266. this._isOccluded = false;
  18267. return;
  18268. }
  18269. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18270. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18271. if (isOcclusionQueryAvailable) {
  18272. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18273. this._isOcclusionQueryInProgress = false;
  18274. this._occlusionInternalRetryCounter = 0;
  18275. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18276. }
  18277. else {
  18278. this._occlusionInternalRetryCounter++;
  18279. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18280. this._isOcclusionQueryInProgress = false;
  18281. this._occlusionInternalRetryCounter = 0;
  18282. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18283. // if strict continue the last state of the object.
  18284. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18285. }
  18286. else {
  18287. return;
  18288. }
  18289. }
  18290. }
  18291. var scene = this.getScene();
  18292. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18293. if (!this._occlusionQuery) {
  18294. this._occlusionQuery = engine.createQuery();
  18295. }
  18296. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18297. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18298. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18299. this._isOcclusionQueryInProgress = true;
  18300. };
  18301. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18302. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18303. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18304. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18305. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18306. return AbstractMesh;
  18307. }(BABYLON.TransformNode));
  18308. BABYLON.AbstractMesh = AbstractMesh;
  18309. })(BABYLON || (BABYLON = {}));
  18310. //# sourceMappingURL=babylon.abstractMesh.js.map
  18311. var BABYLON;
  18312. (function (BABYLON) {
  18313. /**
  18314. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18315. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18316. * 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.
  18317. */
  18318. var Light = /** @class */ (function (_super) {
  18319. __extends(Light, _super);
  18320. /**
  18321. * Creates a Light object in the scene.
  18322. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18323. * @param name The firendly name of the light
  18324. * @param scene The scene the light belongs too
  18325. */
  18326. function Light(name, scene) {
  18327. var _this = _super.call(this, name, scene) || this;
  18328. /**
  18329. * Diffuse gives the basic color to an object.
  18330. */
  18331. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  18332. /**
  18333. * Specular produces a highlight color on an object.
  18334. * Note: This is note affecting PBR materials.
  18335. */
  18336. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  18337. /**
  18338. * Strength of the light.
  18339. * Note: By default it is define in the framework own unit.
  18340. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  18341. */
  18342. _this.intensity = 1.0;
  18343. /**
  18344. * Defines how far from the source the light is impacting in scene units.
  18345. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  18346. */
  18347. _this.range = Number.MAX_VALUE;
  18348. /**
  18349. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  18350. * of light.
  18351. */
  18352. _this._photometricScale = 1.0;
  18353. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  18354. _this._radius = 0.00001;
  18355. /**
  18356. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  18357. * exceeding the number allowed of the materials.
  18358. */
  18359. _this.renderPriority = 0;
  18360. /**
  18361. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  18362. * the current shadow generator.
  18363. */
  18364. _this.shadowEnabled = true;
  18365. _this._excludeWithLayerMask = 0;
  18366. _this._includeOnlyWithLayerMask = 0;
  18367. _this._lightmapMode = 0;
  18368. /**
  18369. * @ignore Internal use only.
  18370. */
  18371. _this._excludedMeshesIds = new Array();
  18372. /**
  18373. * @ignore Internal use only.
  18374. */
  18375. _this._includedOnlyMeshesIds = new Array();
  18376. _this.getScene().addLight(_this);
  18377. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  18378. _this._buildUniformLayout();
  18379. _this.includedOnlyMeshes = new Array();
  18380. _this.excludedMeshes = new Array();
  18381. _this._resyncMeshes();
  18382. return _this;
  18383. }
  18384. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  18385. /**
  18386. * If every light affecting the material is in this lightmapMode,
  18387. * material.lightmapTexture adds or multiplies
  18388. * (depends on material.useLightmapAsShadowmap)
  18389. * after every other light calculations.
  18390. */
  18391. get: function () {
  18392. return Light._LIGHTMAP_DEFAULT;
  18393. },
  18394. enumerable: true,
  18395. configurable: true
  18396. });
  18397. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  18398. /**
  18399. * material.lightmapTexture as only diffuse lighting from this light
  18400. * adds only specular lighting from this light
  18401. * adds dynamic shadows
  18402. */
  18403. get: function () {
  18404. return Light._LIGHTMAP_SPECULAR;
  18405. },
  18406. enumerable: true,
  18407. configurable: true
  18408. });
  18409. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  18410. /**
  18411. * material.lightmapTexture as only lighting
  18412. * no light calculation from this light
  18413. * only adds dynamic shadows from this light
  18414. */
  18415. get: function () {
  18416. return Light._LIGHTMAP_SHADOWSONLY;
  18417. },
  18418. enumerable: true,
  18419. configurable: true
  18420. });
  18421. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  18422. /**
  18423. * Each light type uses the default quantity according to its type:
  18424. * point/spot lights use luminous intensity
  18425. * directional lights use illuminance
  18426. */
  18427. get: function () {
  18428. return Light._INTENSITYMODE_AUTOMATIC;
  18429. },
  18430. enumerable: true,
  18431. configurable: true
  18432. });
  18433. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  18434. /**
  18435. * lumen (lm)
  18436. */
  18437. get: function () {
  18438. return Light._INTENSITYMODE_LUMINOUSPOWER;
  18439. },
  18440. enumerable: true,
  18441. configurable: true
  18442. });
  18443. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  18444. /**
  18445. * candela (lm/sr)
  18446. */
  18447. get: function () {
  18448. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  18449. },
  18450. enumerable: true,
  18451. configurable: true
  18452. });
  18453. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  18454. /**
  18455. * lux (lm/m^2)
  18456. */
  18457. get: function () {
  18458. return Light._INTENSITYMODE_ILLUMINANCE;
  18459. },
  18460. enumerable: true,
  18461. configurable: true
  18462. });
  18463. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  18464. /**
  18465. * nit (cd/m^2)
  18466. */
  18467. get: function () {
  18468. return Light._INTENSITYMODE_LUMINANCE;
  18469. },
  18470. enumerable: true,
  18471. configurable: true
  18472. });
  18473. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  18474. /**
  18475. * Light type const id of the point light.
  18476. */
  18477. get: function () {
  18478. return Light._LIGHTTYPEID_POINTLIGHT;
  18479. },
  18480. enumerable: true,
  18481. configurable: true
  18482. });
  18483. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  18484. /**
  18485. * Light type const id of the directional light.
  18486. */
  18487. get: function () {
  18488. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  18489. },
  18490. enumerable: true,
  18491. configurable: true
  18492. });
  18493. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  18494. /**
  18495. * Light type const id of the spot light.
  18496. */
  18497. get: function () {
  18498. return Light._LIGHTTYPEID_SPOTLIGHT;
  18499. },
  18500. enumerable: true,
  18501. configurable: true
  18502. });
  18503. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  18504. /**
  18505. * Light type const id of the hemispheric light.
  18506. */
  18507. get: function () {
  18508. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  18509. },
  18510. enumerable: true,
  18511. configurable: true
  18512. });
  18513. Object.defineProperty(Light.prototype, "intensityMode", {
  18514. /**
  18515. * Gets the photometric scale used to interpret the intensity.
  18516. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18517. */
  18518. get: function () {
  18519. return this._intensityMode;
  18520. },
  18521. /**
  18522. * Sets the photometric scale used to interpret the intensity.
  18523. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18524. */
  18525. set: function (value) {
  18526. this._intensityMode = value;
  18527. this._computePhotometricScale();
  18528. },
  18529. enumerable: true,
  18530. configurable: true
  18531. });
  18532. ;
  18533. ;
  18534. Object.defineProperty(Light.prototype, "radius", {
  18535. /**
  18536. * Gets the light radius used by PBR Materials to simulate soft area lights.
  18537. */
  18538. get: function () {
  18539. return this._radius;
  18540. },
  18541. /**
  18542. * sets the light radius used by PBR Materials to simulate soft area lights.
  18543. */
  18544. set: function (value) {
  18545. this._radius = value;
  18546. this._computePhotometricScale();
  18547. },
  18548. enumerable: true,
  18549. configurable: true
  18550. });
  18551. ;
  18552. ;
  18553. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  18554. /**
  18555. * Gets the only meshes impacted by this light.
  18556. */
  18557. get: function () {
  18558. return this._includedOnlyMeshes;
  18559. },
  18560. /**
  18561. * Sets the only meshes impacted by this light.
  18562. */
  18563. set: function (value) {
  18564. this._includedOnlyMeshes = value;
  18565. this._hookArrayForIncludedOnly(value);
  18566. },
  18567. enumerable: true,
  18568. configurable: true
  18569. });
  18570. Object.defineProperty(Light.prototype, "excludedMeshes", {
  18571. /**
  18572. * Gets the meshes not impacted by this light.
  18573. */
  18574. get: function () {
  18575. return this._excludedMeshes;
  18576. },
  18577. /**
  18578. * Sets the meshes not impacted by this light.
  18579. */
  18580. set: function (value) {
  18581. this._excludedMeshes = value;
  18582. this._hookArrayForExcluded(value);
  18583. },
  18584. enumerable: true,
  18585. configurable: true
  18586. });
  18587. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  18588. /**
  18589. * Gets the layer id use to find what meshes are not impacted by the light.
  18590. * Inactive if 0
  18591. */
  18592. get: function () {
  18593. return this._excludeWithLayerMask;
  18594. },
  18595. /**
  18596. * Sets the layer id use to find what meshes are not impacted by the light.
  18597. * Inactive if 0
  18598. */
  18599. set: function (value) {
  18600. this._excludeWithLayerMask = value;
  18601. this._resyncMeshes();
  18602. },
  18603. enumerable: true,
  18604. configurable: true
  18605. });
  18606. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  18607. /**
  18608. * Gets the layer id use to find what meshes are impacted by the light.
  18609. * Inactive if 0
  18610. */
  18611. get: function () {
  18612. return this._includeOnlyWithLayerMask;
  18613. },
  18614. /**
  18615. * Sets the layer id use to find what meshes are impacted by the light.
  18616. * Inactive if 0
  18617. */
  18618. set: function (value) {
  18619. this._includeOnlyWithLayerMask = value;
  18620. this._resyncMeshes();
  18621. },
  18622. enumerable: true,
  18623. configurable: true
  18624. });
  18625. Object.defineProperty(Light.prototype, "lightmapMode", {
  18626. /**
  18627. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18628. */
  18629. get: function () {
  18630. return this._lightmapMode;
  18631. },
  18632. /**
  18633. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18634. */
  18635. set: function (value) {
  18636. if (this._lightmapMode === value) {
  18637. return;
  18638. }
  18639. this._lightmapMode = value;
  18640. this._markMeshesAsLightDirty();
  18641. },
  18642. enumerable: true,
  18643. configurable: true
  18644. });
  18645. /**
  18646. * Returns the string "Light".
  18647. * @returns the class name
  18648. */
  18649. Light.prototype.getClassName = function () {
  18650. return "Light";
  18651. };
  18652. /**
  18653. * Converts the light information to a readable string for debug purpose.
  18654. * @param fullDetails Supports for multiple levels of logging within scene loading
  18655. * @returns the human readable light info
  18656. */
  18657. Light.prototype.toString = function (fullDetails) {
  18658. var ret = "Name: " + this.name;
  18659. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  18660. if (this.animations) {
  18661. for (var i = 0; i < this.animations.length; i++) {
  18662. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18663. }
  18664. }
  18665. if (fullDetails) {
  18666. }
  18667. return ret;
  18668. };
  18669. /**
  18670. * Set the enabled state of this node.
  18671. * @param value - the new enabled state
  18672. * @see isEnabled
  18673. */
  18674. Light.prototype.setEnabled = function (value) {
  18675. _super.prototype.setEnabled.call(this, value);
  18676. this._resyncMeshes();
  18677. };
  18678. /**
  18679. * Returns the Light associated shadow generator if any.
  18680. * @return the associated shadow generator.
  18681. */
  18682. Light.prototype.getShadowGenerator = function () {
  18683. return this._shadowGenerator;
  18684. };
  18685. /**
  18686. * Returns a Vector3, the absolute light position in the World.
  18687. * @returns the world space position of the light
  18688. */
  18689. Light.prototype.getAbsolutePosition = function () {
  18690. return BABYLON.Vector3.Zero();
  18691. };
  18692. /**
  18693. * Specifies if the light will affect the passed mesh.
  18694. * @param mesh The mesh to test against the light
  18695. * @return true the mesh is affected otherwise, false.
  18696. */
  18697. Light.prototype.canAffectMesh = function (mesh) {
  18698. if (!mesh) {
  18699. return true;
  18700. }
  18701. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  18702. return false;
  18703. }
  18704. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  18705. return false;
  18706. }
  18707. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  18708. return false;
  18709. }
  18710. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  18711. return false;
  18712. }
  18713. return true;
  18714. };
  18715. /**
  18716. * Computes and Returns the light World matrix.
  18717. * @returns the world matrix
  18718. */
  18719. Light.prototype.getWorldMatrix = function () {
  18720. this._currentRenderId = this.getScene().getRenderId();
  18721. var worldMatrix = this._getWorldMatrix();
  18722. if (this.parent && this.parent.getWorldMatrix) {
  18723. if (!this._parentedWorldMatrix) {
  18724. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  18725. }
  18726. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  18727. this._markSyncedWithParent();
  18728. return this._parentedWorldMatrix;
  18729. }
  18730. return worldMatrix;
  18731. };
  18732. /**
  18733. * Sort function to order lights for rendering.
  18734. * @param a First Light object to compare to second.
  18735. * @param b Second Light object to compare first.
  18736. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  18737. */
  18738. Light.CompareLightsPriority = function (a, b) {
  18739. //shadow-casting lights have priority over non-shadow-casting lights
  18740. //the renderPrioirty is a secondary sort criterion
  18741. if (a.shadowEnabled !== b.shadowEnabled) {
  18742. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  18743. }
  18744. return b.renderPriority - a.renderPriority;
  18745. };
  18746. /**
  18747. * Disposes the light.
  18748. */
  18749. Light.prototype.dispose = function () {
  18750. if (this._shadowGenerator) {
  18751. this._shadowGenerator.dispose();
  18752. this._shadowGenerator = null;
  18753. }
  18754. // Animations
  18755. this.getScene().stopAnimation(this);
  18756. // Remove from meshes
  18757. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18758. var mesh = _a[_i];
  18759. mesh._removeLightSource(this);
  18760. }
  18761. this._uniformBuffer.dispose();
  18762. // Remove from scene
  18763. this.getScene().removeLight(this);
  18764. _super.prototype.dispose.call(this);
  18765. };
  18766. /**
  18767. * Returns the light type ID (integer).
  18768. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  18769. */
  18770. Light.prototype.getTypeID = function () {
  18771. return 0;
  18772. };
  18773. /**
  18774. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  18775. * @returns the scaled intensity in intensity mode unit
  18776. */
  18777. Light.prototype.getScaledIntensity = function () {
  18778. return this._photometricScale * this.intensity;
  18779. };
  18780. /**
  18781. * Returns a new Light object, named "name", from the current one.
  18782. * @param name The name of the cloned light
  18783. * @returns the new created light
  18784. */
  18785. Light.prototype.clone = function (name) {
  18786. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  18787. if (!constructor) {
  18788. return null;
  18789. }
  18790. return BABYLON.SerializationHelper.Clone(constructor, this);
  18791. };
  18792. /**
  18793. * Serializes the current light into a Serialization object.
  18794. * @returns the serialized object.
  18795. */
  18796. Light.prototype.serialize = function () {
  18797. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18798. // Type
  18799. serializationObject.type = this.getTypeID();
  18800. // Parent
  18801. if (this.parent) {
  18802. serializationObject.parentId = this.parent.id;
  18803. }
  18804. // Inclusion / exclusions
  18805. if (this.excludedMeshes.length > 0) {
  18806. serializationObject.excludedMeshesIds = [];
  18807. this.excludedMeshes.forEach(function (mesh) {
  18808. serializationObject.excludedMeshesIds.push(mesh.id);
  18809. });
  18810. }
  18811. if (this.includedOnlyMeshes.length > 0) {
  18812. serializationObject.includedOnlyMeshesIds = [];
  18813. this.includedOnlyMeshes.forEach(function (mesh) {
  18814. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  18815. });
  18816. }
  18817. // Animations
  18818. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18819. serializationObject.ranges = this.serializeAnimationRanges();
  18820. return serializationObject;
  18821. };
  18822. /**
  18823. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  18824. * This new light is named "name" and added to the passed scene.
  18825. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  18826. * @param name The friendly name of the light
  18827. * @param scene The scene the new light will belong to
  18828. * @returns the constructor function
  18829. */
  18830. Light.GetConstructorFromName = function (type, name, scene) {
  18831. switch (type) {
  18832. case 0:
  18833. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  18834. case 1:
  18835. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  18836. case 2:
  18837. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  18838. case 3:
  18839. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  18840. }
  18841. return null;
  18842. };
  18843. /**
  18844. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  18845. * @param parsedLight The JSON representation of the light
  18846. * @param scene The scene to create the parsed light in
  18847. * @returns the created light after parsing
  18848. */
  18849. Light.Parse = function (parsedLight, scene) {
  18850. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  18851. if (!constructor) {
  18852. return null;
  18853. }
  18854. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  18855. // Inclusion / exclusions
  18856. if (parsedLight.excludedMeshesIds) {
  18857. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18858. }
  18859. if (parsedLight.includedOnlyMeshesIds) {
  18860. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18861. }
  18862. // Parent
  18863. if (parsedLight.parentId) {
  18864. light._waitingParentId = parsedLight.parentId;
  18865. }
  18866. // Animations
  18867. if (parsedLight.animations) {
  18868. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18869. var parsedAnimation = parsedLight.animations[animationIndex];
  18870. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18871. }
  18872. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  18873. }
  18874. if (parsedLight.autoAnimate) {
  18875. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  18876. }
  18877. return light;
  18878. };
  18879. Light.prototype._hookArrayForExcluded = function (array) {
  18880. var _this = this;
  18881. var oldPush = array.push;
  18882. array.push = function () {
  18883. var items = [];
  18884. for (var _i = 0; _i < arguments.length; _i++) {
  18885. items[_i] = arguments[_i];
  18886. }
  18887. var result = oldPush.apply(array, items);
  18888. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  18889. var item = items_1[_a];
  18890. item._resyncLighSource(_this);
  18891. }
  18892. return result;
  18893. };
  18894. var oldSplice = array.splice;
  18895. array.splice = function (index, deleteCount) {
  18896. var deleted = oldSplice.apply(array, [index, deleteCount]);
  18897. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  18898. var item = deleted_1[_i];
  18899. item._resyncLighSource(_this);
  18900. }
  18901. return deleted;
  18902. };
  18903. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  18904. var item = array_1[_i];
  18905. item._resyncLighSource(this);
  18906. }
  18907. };
  18908. Light.prototype._hookArrayForIncludedOnly = function (array) {
  18909. var _this = this;
  18910. var oldPush = array.push;
  18911. array.push = function () {
  18912. var items = [];
  18913. for (var _i = 0; _i < arguments.length; _i++) {
  18914. items[_i] = arguments[_i];
  18915. }
  18916. var result = oldPush.apply(array, items);
  18917. _this._resyncMeshes();
  18918. return result;
  18919. };
  18920. var oldSplice = array.splice;
  18921. array.splice = function (index, deleteCount) {
  18922. var deleted = oldSplice.apply(array, [index, deleteCount]);
  18923. _this._resyncMeshes();
  18924. return deleted;
  18925. };
  18926. this._resyncMeshes();
  18927. };
  18928. Light.prototype._resyncMeshes = function () {
  18929. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18930. var mesh = _a[_i];
  18931. mesh._resyncLighSource(this);
  18932. }
  18933. };
  18934. /**
  18935. * Forces the meshes to update their light related information in their rendering used effects
  18936. * @ignore Internal Use Only
  18937. */
  18938. Light.prototype._markMeshesAsLightDirty = function () {
  18939. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18940. var mesh = _a[_i];
  18941. if (mesh._lightSources.indexOf(this) !== -1) {
  18942. mesh._markSubMeshesAsLightDirty();
  18943. }
  18944. }
  18945. };
  18946. /**
  18947. * Recomputes the cached photometric scale if needed.
  18948. */
  18949. Light.prototype._computePhotometricScale = function () {
  18950. this._photometricScale = this._getPhotometricScale();
  18951. this.getScene().resetCachedMaterial();
  18952. };
  18953. /**
  18954. * Returns the Photometric Scale according to the light type and intensity mode.
  18955. */
  18956. Light.prototype._getPhotometricScale = function () {
  18957. var photometricScale = 0.0;
  18958. var lightTypeID = this.getTypeID();
  18959. //get photometric mode
  18960. var photometricMode = this.intensityMode;
  18961. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  18962. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  18963. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  18964. }
  18965. else {
  18966. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  18967. }
  18968. }
  18969. //compute photometric scale
  18970. switch (lightTypeID) {
  18971. case Light.LIGHTTYPEID_POINTLIGHT:
  18972. case Light.LIGHTTYPEID_SPOTLIGHT:
  18973. switch (photometricMode) {
  18974. case Light.INTENSITYMODE_LUMINOUSPOWER:
  18975. photometricScale = 1.0 / (4.0 * Math.PI);
  18976. break;
  18977. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  18978. photometricScale = 1.0;
  18979. break;
  18980. case Light.INTENSITYMODE_LUMINANCE:
  18981. photometricScale = this.radius * this.radius;
  18982. break;
  18983. }
  18984. break;
  18985. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  18986. switch (photometricMode) {
  18987. case Light.INTENSITYMODE_ILLUMINANCE:
  18988. photometricScale = 1.0;
  18989. break;
  18990. case Light.INTENSITYMODE_LUMINANCE:
  18991. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  18992. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  18993. var apexAngleRadians = this.radius;
  18994. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  18995. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  18996. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  18997. photometricScale = solidAngle;
  18998. break;
  18999. }
  19000. break;
  19001. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19002. // No fall off in hemisperic light.
  19003. photometricScale = 1.0;
  19004. break;
  19005. }
  19006. return photometricScale;
  19007. };
  19008. /**
  19009. * Reorder the light in the scene according to their defined priority.
  19010. * @ignore Internal Use Only
  19011. */
  19012. Light.prototype._reorderLightsInScene = function () {
  19013. var scene = this.getScene();
  19014. if (this._renderPriority != 0) {
  19015. scene.requireLightSorting = true;
  19016. }
  19017. this.getScene().sortLightsByPriority();
  19018. };
  19019. //lightmapMode Consts
  19020. Light._LIGHTMAP_DEFAULT = 0;
  19021. Light._LIGHTMAP_SPECULAR = 1;
  19022. Light._LIGHTMAP_SHADOWSONLY = 2;
  19023. // Intensity Mode Consts
  19024. Light._INTENSITYMODE_AUTOMATIC = 0;
  19025. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19026. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19027. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19028. Light._INTENSITYMODE_LUMINANCE = 4;
  19029. // Light types ids const.
  19030. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19031. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19032. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19033. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19034. __decorate([
  19035. BABYLON.serializeAsColor3()
  19036. ], Light.prototype, "diffuse", void 0);
  19037. __decorate([
  19038. BABYLON.serializeAsColor3()
  19039. ], Light.prototype, "specular", void 0);
  19040. __decorate([
  19041. BABYLON.serialize()
  19042. ], Light.prototype, "intensity", void 0);
  19043. __decorate([
  19044. BABYLON.serialize()
  19045. ], Light.prototype, "range", void 0);
  19046. __decorate([
  19047. BABYLON.serialize()
  19048. ], Light.prototype, "intensityMode", null);
  19049. __decorate([
  19050. BABYLON.serialize()
  19051. ], Light.prototype, "radius", null);
  19052. __decorate([
  19053. BABYLON.serialize()
  19054. ], Light.prototype, "_renderPriority", void 0);
  19055. __decorate([
  19056. BABYLON.expandToProperty("_reorderLightsInScene")
  19057. ], Light.prototype, "renderPriority", void 0);
  19058. __decorate([
  19059. BABYLON.serialize()
  19060. ], Light.prototype, "shadowEnabled", void 0);
  19061. __decorate([
  19062. BABYLON.serialize("excludeWithLayerMask")
  19063. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19064. __decorate([
  19065. BABYLON.serialize("includeOnlyWithLayerMask")
  19066. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19067. __decorate([
  19068. BABYLON.serialize("lightmapMode")
  19069. ], Light.prototype, "_lightmapMode", void 0);
  19070. return Light;
  19071. }(BABYLON.Node));
  19072. BABYLON.Light = Light;
  19073. })(BABYLON || (BABYLON = {}));
  19074. //# sourceMappingURL=babylon.light.js.map
  19075. var BABYLON;
  19076. (function (BABYLON) {
  19077. var Camera = /** @class */ (function (_super) {
  19078. __extends(Camera, _super);
  19079. function Camera(name, position, scene) {
  19080. var _this = _super.call(this, name, scene) || this;
  19081. /**
  19082. * The vector the camera should consider as up.
  19083. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19084. */
  19085. _this.upVector = BABYLON.Vector3.Up();
  19086. _this.orthoLeft = null;
  19087. _this.orthoRight = null;
  19088. _this.orthoBottom = null;
  19089. _this.orthoTop = null;
  19090. /**
  19091. * FOV is set in Radians. (default is 0.8)
  19092. */
  19093. _this.fov = 0.8;
  19094. _this.minZ = 1;
  19095. _this.maxZ = 10000.0;
  19096. _this.inertia = 0.9;
  19097. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19098. _this.isIntermediate = false;
  19099. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19100. /**
  19101. * Restricts the camera to viewing objects with the same layerMask.
  19102. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19103. */
  19104. _this.layerMask = 0x0FFFFFFF;
  19105. /**
  19106. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19107. */
  19108. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19109. // Camera rig members
  19110. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19111. _this._rigCameras = new Array();
  19112. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19113. _this._skipRendering = false;
  19114. _this.customRenderTargets = new Array();
  19115. // Observables
  19116. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19117. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19118. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19119. _this.onRestoreStateObservable = new BABYLON.Observable();
  19120. // Cache
  19121. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19122. _this._projectionMatrix = new BABYLON.Matrix();
  19123. _this._doNotComputeProjectionMatrix = false;
  19124. _this._postProcesses = new Array();
  19125. _this._transformMatrix = BABYLON.Matrix.Zero();
  19126. _this._activeMeshes = new BABYLON.SmartArray(256);
  19127. _this._globalPosition = BABYLON.Vector3.Zero();
  19128. _this._refreshFrustumPlanes = true;
  19129. _this.getScene().addCamera(_this);
  19130. if (!_this.getScene().activeCamera) {
  19131. _this.getScene().activeCamera = _this;
  19132. }
  19133. _this.position = position;
  19134. return _this;
  19135. }
  19136. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19137. get: function () {
  19138. return Camera._PERSPECTIVE_CAMERA;
  19139. },
  19140. enumerable: true,
  19141. configurable: true
  19142. });
  19143. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19144. get: function () {
  19145. return Camera._ORTHOGRAPHIC_CAMERA;
  19146. },
  19147. enumerable: true,
  19148. configurable: true
  19149. });
  19150. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19151. /**
  19152. * This is the default FOV mode for perspective cameras.
  19153. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19154. *
  19155. */
  19156. get: function () {
  19157. return Camera._FOVMODE_VERTICAL_FIXED;
  19158. },
  19159. enumerable: true,
  19160. configurable: true
  19161. });
  19162. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19163. /**
  19164. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19165. *
  19166. */
  19167. get: function () {
  19168. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19169. },
  19170. enumerable: true,
  19171. configurable: true
  19172. });
  19173. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19174. get: function () {
  19175. return Camera._RIG_MODE_NONE;
  19176. },
  19177. enumerable: true,
  19178. configurable: true
  19179. });
  19180. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19181. get: function () {
  19182. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19183. },
  19184. enumerable: true,
  19185. configurable: true
  19186. });
  19187. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19188. get: function () {
  19189. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19190. },
  19191. enumerable: true,
  19192. configurable: true
  19193. });
  19194. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19195. get: function () {
  19196. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19197. },
  19198. enumerable: true,
  19199. configurable: true
  19200. });
  19201. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19202. get: function () {
  19203. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19204. },
  19205. enumerable: true,
  19206. configurable: true
  19207. });
  19208. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19209. get: function () {
  19210. return Camera._RIG_MODE_VR;
  19211. },
  19212. enumerable: true,
  19213. configurable: true
  19214. });
  19215. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19216. get: function () {
  19217. return Camera._RIG_MODE_WEBVR;
  19218. },
  19219. enumerable: true,
  19220. configurable: true
  19221. });
  19222. /**
  19223. * Store current camera state (fov, position, etc..)
  19224. */
  19225. Camera.prototype.storeState = function () {
  19226. this._stateStored = true;
  19227. this._storedFov = this.fov;
  19228. return this;
  19229. };
  19230. /**
  19231. * Restores the camera state values if it has been stored. You must call storeState() first
  19232. */
  19233. Camera.prototype._restoreStateValues = function () {
  19234. if (!this._stateStored) {
  19235. return false;
  19236. }
  19237. this.fov = this._storedFov;
  19238. return true;
  19239. };
  19240. /**
  19241. * Restored camera state. You must call storeState() first
  19242. */
  19243. Camera.prototype.restoreState = function () {
  19244. if (this._restoreStateValues()) {
  19245. this.onRestoreStateObservable.notifyObservers(this);
  19246. return true;
  19247. }
  19248. return false;
  19249. };
  19250. Camera.prototype.getClassName = function () {
  19251. return "Camera";
  19252. };
  19253. /**
  19254. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19255. */
  19256. Camera.prototype.toString = function (fullDetails) {
  19257. var ret = "Name: " + this.name;
  19258. ret += ", type: " + this.getClassName();
  19259. if (this.animations) {
  19260. for (var i = 0; i < this.animations.length; i++) {
  19261. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19262. }
  19263. }
  19264. if (fullDetails) {
  19265. }
  19266. return ret;
  19267. };
  19268. Object.defineProperty(Camera.prototype, "globalPosition", {
  19269. get: function () {
  19270. return this._globalPosition;
  19271. },
  19272. enumerable: true,
  19273. configurable: true
  19274. });
  19275. Camera.prototype.getActiveMeshes = function () {
  19276. return this._activeMeshes;
  19277. };
  19278. Camera.prototype.isActiveMesh = function (mesh) {
  19279. return (this._activeMeshes.indexOf(mesh) !== -1);
  19280. };
  19281. //Cache
  19282. Camera.prototype._initCache = function () {
  19283. _super.prototype._initCache.call(this);
  19284. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19285. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19286. this._cache.mode = undefined;
  19287. this._cache.minZ = undefined;
  19288. this._cache.maxZ = undefined;
  19289. this._cache.fov = undefined;
  19290. this._cache.fovMode = undefined;
  19291. this._cache.aspectRatio = undefined;
  19292. this._cache.orthoLeft = undefined;
  19293. this._cache.orthoRight = undefined;
  19294. this._cache.orthoBottom = undefined;
  19295. this._cache.orthoTop = undefined;
  19296. this._cache.renderWidth = undefined;
  19297. this._cache.renderHeight = undefined;
  19298. };
  19299. Camera.prototype._updateCache = function (ignoreParentClass) {
  19300. if (!ignoreParentClass) {
  19301. _super.prototype._updateCache.call(this);
  19302. }
  19303. this._cache.position.copyFrom(this.position);
  19304. this._cache.upVector.copyFrom(this.upVector);
  19305. };
  19306. // Synchronized
  19307. Camera.prototype._isSynchronized = function () {
  19308. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19309. };
  19310. Camera.prototype._isSynchronizedViewMatrix = function () {
  19311. if (!_super.prototype._isSynchronized.call(this))
  19312. return false;
  19313. return this._cache.position.equals(this.position)
  19314. && this._cache.upVector.equals(this.upVector)
  19315. && this.isSynchronizedWithParent();
  19316. };
  19317. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19318. var check = this._cache.mode === this.mode
  19319. && this._cache.minZ === this.minZ
  19320. && this._cache.maxZ === this.maxZ;
  19321. if (!check) {
  19322. return false;
  19323. }
  19324. var engine = this.getEngine();
  19325. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19326. check = this._cache.fov === this.fov
  19327. && this._cache.fovMode === this.fovMode
  19328. && this._cache.aspectRatio === engine.getAspectRatio(this);
  19329. }
  19330. else {
  19331. check = this._cache.orthoLeft === this.orthoLeft
  19332. && this._cache.orthoRight === this.orthoRight
  19333. && this._cache.orthoBottom === this.orthoBottom
  19334. && this._cache.orthoTop === this.orthoTop
  19335. && this._cache.renderWidth === engine.getRenderWidth()
  19336. && this._cache.renderHeight === engine.getRenderHeight();
  19337. }
  19338. return check;
  19339. };
  19340. // Controls
  19341. Camera.prototype.attachControl = function (element, noPreventDefault) {
  19342. };
  19343. Camera.prototype.detachControl = function (element) {
  19344. };
  19345. Camera.prototype.update = function () {
  19346. this._checkInputs();
  19347. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19348. this._updateRigCameras();
  19349. }
  19350. };
  19351. Camera.prototype._checkInputs = function () {
  19352. this.onAfterCheckInputsObservable.notifyObservers(this);
  19353. };
  19354. Object.defineProperty(Camera.prototype, "rigCameras", {
  19355. get: function () {
  19356. return this._rigCameras;
  19357. },
  19358. enumerable: true,
  19359. configurable: true
  19360. });
  19361. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  19362. get: function () {
  19363. return this._rigPostProcess;
  19364. },
  19365. enumerable: true,
  19366. configurable: true
  19367. });
  19368. Camera.prototype._cascadePostProcessesToRigCams = function () {
  19369. // invalidate framebuffer
  19370. if (this._postProcesses.length > 0) {
  19371. this._postProcesses[0].markTextureDirty();
  19372. }
  19373. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  19374. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  19375. var cam = this._rigCameras[i];
  19376. var rigPostProcess = cam._rigPostProcess;
  19377. // for VR rig, there does not have to be a post process
  19378. if (rigPostProcess) {
  19379. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  19380. if (isPass) {
  19381. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  19382. cam.isIntermediate = this._postProcesses.length === 0;
  19383. }
  19384. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  19385. rigPostProcess.markTextureDirty();
  19386. }
  19387. else {
  19388. cam._postProcesses = this._postProcesses.slice(0);
  19389. }
  19390. }
  19391. };
  19392. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  19393. if (insertAt === void 0) { insertAt = null; }
  19394. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  19395. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  19396. return 0;
  19397. }
  19398. if (insertAt == null || insertAt < 0) {
  19399. this._postProcesses.push(postProcess);
  19400. }
  19401. else {
  19402. this._postProcesses.splice(insertAt, 0, postProcess);
  19403. }
  19404. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19405. return this._postProcesses.indexOf(postProcess);
  19406. };
  19407. Camera.prototype.detachPostProcess = function (postProcess) {
  19408. var idx = this._postProcesses.indexOf(postProcess);
  19409. if (idx !== -1) {
  19410. this._postProcesses.splice(idx, 1);
  19411. }
  19412. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19413. };
  19414. Camera.prototype.getWorldMatrix = function () {
  19415. if (!this._worldMatrix) {
  19416. this._worldMatrix = BABYLON.Matrix.Identity();
  19417. }
  19418. var viewMatrix = this.getViewMatrix();
  19419. viewMatrix.invertToRef(this._worldMatrix);
  19420. return this._worldMatrix;
  19421. };
  19422. Camera.prototype._getViewMatrix = function () {
  19423. return BABYLON.Matrix.Identity();
  19424. };
  19425. Camera.prototype.getViewMatrix = function (force) {
  19426. if (!force && this._isSynchronizedViewMatrix()) {
  19427. return this._computedViewMatrix;
  19428. }
  19429. this.updateCache();
  19430. this._computedViewMatrix = this._getViewMatrix();
  19431. this._currentRenderId = this.getScene().getRenderId();
  19432. this._refreshFrustumPlanes = true;
  19433. if (!this.parent || !this.parent.getWorldMatrix) {
  19434. this._globalPosition.copyFrom(this.position);
  19435. }
  19436. else {
  19437. if (!this._worldMatrix) {
  19438. this._worldMatrix = BABYLON.Matrix.Identity();
  19439. }
  19440. this._computedViewMatrix.invertToRef(this._worldMatrix);
  19441. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  19442. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  19443. this._computedViewMatrix.invert();
  19444. this._markSyncedWithParent();
  19445. }
  19446. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  19447. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  19448. }
  19449. this.onViewMatrixChangedObservable.notifyObservers(this);
  19450. return this._computedViewMatrix;
  19451. };
  19452. Camera.prototype.freezeProjectionMatrix = function (projection) {
  19453. this._doNotComputeProjectionMatrix = true;
  19454. if (projection !== undefined) {
  19455. this._projectionMatrix = projection;
  19456. }
  19457. };
  19458. ;
  19459. Camera.prototype.unfreezeProjectionMatrix = function () {
  19460. this._doNotComputeProjectionMatrix = false;
  19461. };
  19462. ;
  19463. Camera.prototype.getProjectionMatrix = function (force) {
  19464. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  19465. return this._projectionMatrix;
  19466. }
  19467. // Cache
  19468. this._cache.mode = this.mode;
  19469. this._cache.minZ = this.minZ;
  19470. this._cache.maxZ = this.maxZ;
  19471. // Matrix
  19472. this._refreshFrustumPlanes = true;
  19473. var engine = this.getEngine();
  19474. var scene = this.getScene();
  19475. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19476. this._cache.fov = this.fov;
  19477. this._cache.fovMode = this.fovMode;
  19478. this._cache.aspectRatio = engine.getAspectRatio(this);
  19479. if (this.minZ <= 0) {
  19480. this.minZ = 0.1;
  19481. }
  19482. if (scene.useRightHandedSystem) {
  19483. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19484. }
  19485. else {
  19486. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19487. }
  19488. }
  19489. else {
  19490. var halfWidth = engine.getRenderWidth() / 2.0;
  19491. var halfHeight = engine.getRenderHeight() / 2.0;
  19492. if (scene.useRightHandedSystem) {
  19493. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19494. }
  19495. else {
  19496. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19497. }
  19498. this._cache.orthoLeft = this.orthoLeft;
  19499. this._cache.orthoRight = this.orthoRight;
  19500. this._cache.orthoBottom = this.orthoBottom;
  19501. this._cache.orthoTop = this.orthoTop;
  19502. this._cache.renderWidth = engine.getRenderWidth();
  19503. this._cache.renderHeight = engine.getRenderHeight();
  19504. }
  19505. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  19506. return this._projectionMatrix;
  19507. };
  19508. Camera.prototype.getTranformationMatrix = function () {
  19509. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  19510. return this._transformMatrix;
  19511. };
  19512. Camera.prototype.updateFrustumPlanes = function () {
  19513. if (!this._refreshFrustumPlanes) {
  19514. return;
  19515. }
  19516. this.getTranformationMatrix();
  19517. if (!this._frustumPlanes) {
  19518. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  19519. }
  19520. else {
  19521. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  19522. }
  19523. this._refreshFrustumPlanes = false;
  19524. };
  19525. Camera.prototype.isInFrustum = function (target) {
  19526. this.updateFrustumPlanes();
  19527. return target.isInFrustum(this._frustumPlanes);
  19528. };
  19529. Camera.prototype.isCompletelyInFrustum = function (target) {
  19530. this.updateFrustumPlanes();
  19531. return target.isCompletelyInFrustum(this._frustumPlanes);
  19532. };
  19533. Camera.prototype.getForwardRay = function (length, transform, origin) {
  19534. if (length === void 0) { length = 100; }
  19535. if (!transform) {
  19536. transform = this.getWorldMatrix();
  19537. }
  19538. if (!origin) {
  19539. origin = this.position;
  19540. }
  19541. var forward = new BABYLON.Vector3(0, 0, 1);
  19542. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  19543. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  19544. return new BABYLON.Ray(origin, direction, length);
  19545. };
  19546. Camera.prototype.dispose = function () {
  19547. // Observables
  19548. this.onViewMatrixChangedObservable.clear();
  19549. this.onProjectionMatrixChangedObservable.clear();
  19550. this.onAfterCheckInputsObservable.clear();
  19551. this.onRestoreStateObservable.clear();
  19552. // Inputs
  19553. if (this.inputs) {
  19554. this.inputs.clear();
  19555. }
  19556. // Animations
  19557. this.getScene().stopAnimation(this);
  19558. // Remove from scene
  19559. this.getScene().removeCamera(this);
  19560. while (this._rigCameras.length > 0) {
  19561. var camera = this._rigCameras.pop();
  19562. if (camera) {
  19563. camera.dispose();
  19564. }
  19565. }
  19566. // Postprocesses
  19567. if (this._rigPostProcess) {
  19568. this._rigPostProcess.dispose(this);
  19569. this._rigPostProcess = null;
  19570. this._postProcesses = [];
  19571. }
  19572. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19573. this._rigPostProcess = null;
  19574. this._postProcesses = [];
  19575. }
  19576. else {
  19577. var i = this._postProcesses.length;
  19578. while (--i >= 0) {
  19579. this._postProcesses[i].dispose(this);
  19580. }
  19581. }
  19582. // Render targets
  19583. var i = this.customRenderTargets.length;
  19584. while (--i >= 0) {
  19585. this.customRenderTargets[i].dispose();
  19586. }
  19587. this.customRenderTargets = [];
  19588. // Active Meshes
  19589. this._activeMeshes.dispose();
  19590. _super.prototype.dispose.call(this);
  19591. };
  19592. Object.defineProperty(Camera.prototype, "leftCamera", {
  19593. // ---- Camera rigs section ----
  19594. get: function () {
  19595. if (this._rigCameras.length < 1) {
  19596. return null;
  19597. }
  19598. return this._rigCameras[0];
  19599. },
  19600. enumerable: true,
  19601. configurable: true
  19602. });
  19603. Object.defineProperty(Camera.prototype, "rightCamera", {
  19604. get: function () {
  19605. if (this._rigCameras.length < 2) {
  19606. return null;
  19607. }
  19608. return this._rigCameras[1];
  19609. },
  19610. enumerable: true,
  19611. configurable: true
  19612. });
  19613. Camera.prototype.getLeftTarget = function () {
  19614. if (this._rigCameras.length < 1) {
  19615. return null;
  19616. }
  19617. return this._rigCameras[0].getTarget();
  19618. };
  19619. Camera.prototype.getRightTarget = function () {
  19620. if (this._rigCameras.length < 2) {
  19621. return null;
  19622. }
  19623. return this._rigCameras[1].getTarget();
  19624. };
  19625. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  19626. if (this.cameraRigMode === mode) {
  19627. return;
  19628. }
  19629. while (this._rigCameras.length > 0) {
  19630. var camera = this._rigCameras.pop();
  19631. if (camera) {
  19632. camera.dispose();
  19633. }
  19634. }
  19635. this.cameraRigMode = mode;
  19636. this._cameraRigParams = {};
  19637. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  19638. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  19639. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  19640. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  19641. // create the rig cameras, unless none
  19642. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19643. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  19644. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  19645. if (leftCamera && rightCamera) {
  19646. this._rigCameras.push(leftCamera);
  19647. this._rigCameras.push(rightCamera);
  19648. }
  19649. }
  19650. switch (this.cameraRigMode) {
  19651. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  19652. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19653. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  19654. break;
  19655. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  19656. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  19657. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  19658. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19659. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19660. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  19661. break;
  19662. case Camera.RIG_MODE_VR:
  19663. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  19664. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  19665. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19666. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19667. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  19668. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  19669. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  19670. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  19671. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19672. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19673. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  19674. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  19675. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  19676. if (metrics.compensateDistortion) {
  19677. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  19678. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  19679. }
  19680. break;
  19681. case Camera.RIG_MODE_WEBVR:
  19682. if (rigParams.vrDisplay) {
  19683. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  19684. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  19685. //Left eye
  19686. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19687. this._rigCameras[0].setCameraRigParameter("left", true);
  19688. //leaving this for future reference
  19689. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  19690. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  19691. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  19692. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19693. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19694. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19695. this._rigCameras[0].parent = this;
  19696. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  19697. //Right eye
  19698. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19699. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  19700. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  19701. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  19702. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19703. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19704. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19705. this._rigCameras[1].parent = this;
  19706. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  19707. if (Camera.UseAlternateWebVRRendering) {
  19708. this._rigCameras[1]._skipRendering = true;
  19709. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  19710. }
  19711. }
  19712. break;
  19713. }
  19714. this._cascadePostProcessesToRigCams();
  19715. this.update();
  19716. };
  19717. Camera.prototype._getVRProjectionMatrix = function () {
  19718. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  19719. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  19720. return this._projectionMatrix;
  19721. };
  19722. Camera.prototype._updateCameraRotationMatrix = function () {
  19723. //Here for WebVR
  19724. };
  19725. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  19726. //Here for WebVR
  19727. };
  19728. /**
  19729. * This function MUST be overwritten by the different WebVR cameras available.
  19730. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19731. */
  19732. Camera.prototype._getWebVRProjectionMatrix = function () {
  19733. return BABYLON.Matrix.Identity();
  19734. };
  19735. /**
  19736. * This function MUST be overwritten by the different WebVR cameras available.
  19737. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19738. */
  19739. Camera.prototype._getWebVRViewMatrix = function () {
  19740. return BABYLON.Matrix.Identity();
  19741. };
  19742. Camera.prototype.setCameraRigParameter = function (name, value) {
  19743. if (!this._cameraRigParams) {
  19744. this._cameraRigParams = {};
  19745. }
  19746. this._cameraRigParams[name] = value;
  19747. //provisionnally:
  19748. if (name === "interaxialDistance") {
  19749. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  19750. }
  19751. };
  19752. /**
  19753. * needs to be overridden by children so sub has required properties to be copied
  19754. */
  19755. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  19756. return null;
  19757. };
  19758. /**
  19759. * May need to be overridden by children
  19760. */
  19761. Camera.prototype._updateRigCameras = function () {
  19762. for (var i = 0; i < this._rigCameras.length; i++) {
  19763. this._rigCameras[i].minZ = this.minZ;
  19764. this._rigCameras[i].maxZ = this.maxZ;
  19765. this._rigCameras[i].fov = this.fov;
  19766. }
  19767. // only update viewport when ANAGLYPH
  19768. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  19769. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  19770. }
  19771. };
  19772. Camera.prototype._setupInputs = function () {
  19773. };
  19774. Camera.prototype.serialize = function () {
  19775. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19776. // Type
  19777. serializationObject.type = this.getClassName();
  19778. // Parent
  19779. if (this.parent) {
  19780. serializationObject.parentId = this.parent.id;
  19781. }
  19782. if (this.inputs) {
  19783. this.inputs.serialize(serializationObject);
  19784. }
  19785. // Animations
  19786. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19787. serializationObject.ranges = this.serializeAnimationRanges();
  19788. return serializationObject;
  19789. };
  19790. Camera.prototype.clone = function (name) {
  19791. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  19792. };
  19793. Camera.prototype.getDirection = function (localAxis) {
  19794. var result = BABYLON.Vector3.Zero();
  19795. this.getDirectionToRef(localAxis, result);
  19796. return result;
  19797. };
  19798. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  19799. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19800. };
  19801. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  19802. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  19803. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  19804. switch (type) {
  19805. case "ArcRotateCamera":
  19806. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  19807. case "DeviceOrientationCamera":
  19808. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  19809. case "FollowCamera":
  19810. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  19811. case "ArcFollowCamera":
  19812. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  19813. case "GamepadCamera":
  19814. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19815. case "TouchCamera":
  19816. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  19817. case "VirtualJoysticksCamera":
  19818. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  19819. case "WebVRFreeCamera":
  19820. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19821. case "WebVRGamepadCamera":
  19822. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19823. case "VRDeviceOrientationFreeCamera":
  19824. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19825. case "VRDeviceOrientationGamepadCamera":
  19826. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19827. case "AnaglyphArcRotateCamera":
  19828. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19829. case "AnaglyphFreeCamera":
  19830. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19831. case "AnaglyphGamepadCamera":
  19832. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19833. case "AnaglyphUniversalCamera":
  19834. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19835. case "StereoscopicArcRotateCamera":
  19836. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19837. case "StereoscopicFreeCamera":
  19838. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19839. case "StereoscopicGamepadCamera":
  19840. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19841. case "StereoscopicUniversalCamera":
  19842. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19843. case "FreeCamera":// Forcing Universal here
  19844. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  19845. default:// Universal Camera is the default value
  19846. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  19847. }
  19848. };
  19849. Camera.prototype.computeWorldMatrix = function () {
  19850. return this.getWorldMatrix();
  19851. };
  19852. Camera.Parse = function (parsedCamera, scene) {
  19853. var type = parsedCamera.type;
  19854. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  19855. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  19856. // Parent
  19857. if (parsedCamera.parentId) {
  19858. camera._waitingParentId = parsedCamera.parentId;
  19859. }
  19860. //If camera has an input manager, let it parse inputs settings
  19861. if (camera.inputs) {
  19862. camera.inputs.parse(parsedCamera);
  19863. camera._setupInputs();
  19864. }
  19865. if (camera.setPosition) {
  19866. camera.position.copyFromFloats(0, 0, 0);
  19867. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  19868. }
  19869. // Target
  19870. if (parsedCamera.target) {
  19871. if (camera.setTarget) {
  19872. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19873. }
  19874. }
  19875. // Apply 3d rig, when found
  19876. if (parsedCamera.cameraRigMode) {
  19877. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19878. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19879. }
  19880. // Animations
  19881. if (parsedCamera.animations) {
  19882. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19883. var parsedAnimation = parsedCamera.animations[animationIndex];
  19884. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19885. }
  19886. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  19887. }
  19888. if (parsedCamera.autoAnimate) {
  19889. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  19890. }
  19891. return camera;
  19892. };
  19893. // Statics
  19894. Camera._PERSPECTIVE_CAMERA = 0;
  19895. Camera._ORTHOGRAPHIC_CAMERA = 1;
  19896. Camera._FOVMODE_VERTICAL_FIXED = 0;
  19897. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  19898. Camera._RIG_MODE_NONE = 0;
  19899. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  19900. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  19901. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  19902. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  19903. Camera._RIG_MODE_VR = 20;
  19904. Camera._RIG_MODE_WEBVR = 21;
  19905. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  19906. Camera.UseAlternateWebVRRendering = false;
  19907. __decorate([
  19908. BABYLON.serializeAsVector3()
  19909. ], Camera.prototype, "position", void 0);
  19910. __decorate([
  19911. BABYLON.serializeAsVector3()
  19912. ], Camera.prototype, "upVector", void 0);
  19913. __decorate([
  19914. BABYLON.serialize()
  19915. ], Camera.prototype, "orthoLeft", void 0);
  19916. __decorate([
  19917. BABYLON.serialize()
  19918. ], Camera.prototype, "orthoRight", void 0);
  19919. __decorate([
  19920. BABYLON.serialize()
  19921. ], Camera.prototype, "orthoBottom", void 0);
  19922. __decorate([
  19923. BABYLON.serialize()
  19924. ], Camera.prototype, "orthoTop", void 0);
  19925. __decorate([
  19926. BABYLON.serialize()
  19927. ], Camera.prototype, "fov", void 0);
  19928. __decorate([
  19929. BABYLON.serialize()
  19930. ], Camera.prototype, "minZ", void 0);
  19931. __decorate([
  19932. BABYLON.serialize()
  19933. ], Camera.prototype, "maxZ", void 0);
  19934. __decorate([
  19935. BABYLON.serialize()
  19936. ], Camera.prototype, "inertia", void 0);
  19937. __decorate([
  19938. BABYLON.serialize()
  19939. ], Camera.prototype, "mode", void 0);
  19940. __decorate([
  19941. BABYLON.serialize()
  19942. ], Camera.prototype, "layerMask", void 0);
  19943. __decorate([
  19944. BABYLON.serialize()
  19945. ], Camera.prototype, "fovMode", void 0);
  19946. __decorate([
  19947. BABYLON.serialize()
  19948. ], Camera.prototype, "cameraRigMode", void 0);
  19949. __decorate([
  19950. BABYLON.serialize()
  19951. ], Camera.prototype, "interaxialDistance", void 0);
  19952. __decorate([
  19953. BABYLON.serialize()
  19954. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  19955. return Camera;
  19956. }(BABYLON.Node));
  19957. BABYLON.Camera = Camera;
  19958. })(BABYLON || (BABYLON = {}));
  19959. //# sourceMappingURL=babylon.camera.js.map
  19960. var BABYLON;
  19961. (function (BABYLON) {
  19962. var RenderingManager = /** @class */ (function () {
  19963. function RenderingManager(scene) {
  19964. this._renderingGroups = new Array();
  19965. this._autoClearDepthStencil = {};
  19966. this._customOpaqueSortCompareFn = {};
  19967. this._customAlphaTestSortCompareFn = {};
  19968. this._customTransparentSortCompareFn = {};
  19969. this._renderinGroupInfo = null;
  19970. this._scene = scene;
  19971. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  19972. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  19973. }
  19974. }
  19975. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  19976. if (depth === void 0) { depth = true; }
  19977. if (stencil === void 0) { stencil = true; }
  19978. if (this._depthStencilBufferAlreadyCleaned) {
  19979. return;
  19980. }
  19981. this._scene.getEngine().clear(null, false, depth, stencil);
  19982. this._depthStencilBufferAlreadyCleaned = true;
  19983. };
  19984. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  19985. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  19986. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  19987. var info = null;
  19988. if (observable) {
  19989. if (!this._renderinGroupInfo) {
  19990. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  19991. }
  19992. info = this._renderinGroupInfo;
  19993. info.scene = this._scene;
  19994. info.camera = this._scene.activeCamera;
  19995. }
  19996. // Dispatch sprites
  19997. if (renderSprites) {
  19998. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  19999. var manager = this._scene.spriteManagers[index];
  20000. this.dispatchSprites(manager);
  20001. }
  20002. }
  20003. // Render
  20004. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20005. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20006. var renderingGroup = this._renderingGroups[index];
  20007. if (!renderingGroup && !observable)
  20008. continue;
  20009. var renderingGroupMask = 0;
  20010. // Fire PRECLEAR stage
  20011. if (observable && info) {
  20012. renderingGroupMask = Math.pow(2, index);
  20013. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20014. info.renderingGroupId = index;
  20015. observable.notifyObservers(info, renderingGroupMask);
  20016. }
  20017. // Clear depth/stencil if needed
  20018. if (RenderingManager.AUTOCLEAR) {
  20019. var autoClear = this._autoClearDepthStencil[index];
  20020. if (autoClear && autoClear.autoClear) {
  20021. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20022. }
  20023. }
  20024. if (observable && info) {
  20025. // Fire PREOPAQUE stage
  20026. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20027. observable.notifyObservers(info, renderingGroupMask);
  20028. // Fire PRETRANSPARENT stage
  20029. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20030. observable.notifyObservers(info, renderingGroupMask);
  20031. }
  20032. if (renderingGroup)
  20033. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20034. // Fire POSTTRANSPARENT stage
  20035. if (observable && info) {
  20036. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20037. observable.notifyObservers(info, renderingGroupMask);
  20038. }
  20039. }
  20040. };
  20041. RenderingManager.prototype.reset = function () {
  20042. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20043. var renderingGroup = this._renderingGroups[index];
  20044. if (renderingGroup) {
  20045. renderingGroup.prepare();
  20046. }
  20047. }
  20048. };
  20049. RenderingManager.prototype.dispose = function () {
  20050. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20051. var renderingGroup = this._renderingGroups[index];
  20052. if (renderingGroup) {
  20053. renderingGroup.dispose();
  20054. }
  20055. }
  20056. this._renderingGroups.length = 0;
  20057. };
  20058. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20059. if (this._renderingGroups[renderingGroupId] === undefined) {
  20060. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20061. }
  20062. };
  20063. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20064. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20065. this._prepareRenderingGroup(renderingGroupId);
  20066. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20067. };
  20068. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20069. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20070. this._prepareRenderingGroup(renderingGroupId);
  20071. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20072. };
  20073. /**
  20074. * @param subMesh The submesh to dispatch
  20075. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20076. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20077. */
  20078. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20079. if (mesh === undefined) {
  20080. mesh = subMesh.getMesh();
  20081. }
  20082. var renderingGroupId = mesh.renderingGroupId || 0;
  20083. this._prepareRenderingGroup(renderingGroupId);
  20084. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20085. };
  20086. /**
  20087. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20088. * This allowed control for front to back rendering or reversly depending of the special needs.
  20089. *
  20090. * @param renderingGroupId The rendering group id corresponding to its index
  20091. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20092. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20093. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20094. */
  20095. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20096. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20097. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20098. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20099. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20100. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20101. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20102. if (this._renderingGroups[renderingGroupId]) {
  20103. var group = this._renderingGroups[renderingGroupId];
  20104. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20105. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20106. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20107. }
  20108. };
  20109. /**
  20110. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20111. *
  20112. * @param renderingGroupId The rendering group id corresponding to its index
  20113. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20114. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20115. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20116. */
  20117. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20118. if (depth === void 0) { depth = true; }
  20119. if (stencil === void 0) { stencil = true; }
  20120. this._autoClearDepthStencil[renderingGroupId] = {
  20121. autoClear: autoClearDepthStencil,
  20122. depth: depth,
  20123. stencil: stencil
  20124. };
  20125. };
  20126. /**
  20127. * The max id used for rendering groups (not included)
  20128. */
  20129. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20130. /**
  20131. * The min id used for rendering groups (included)
  20132. */
  20133. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20134. /**
  20135. * Used to globally prevent autoclearing scenes.
  20136. */
  20137. RenderingManager.AUTOCLEAR = true;
  20138. return RenderingManager;
  20139. }());
  20140. BABYLON.RenderingManager = RenderingManager;
  20141. })(BABYLON || (BABYLON = {}));
  20142. //# sourceMappingURL=babylon.renderingManager.js.map
  20143. var BABYLON;
  20144. (function (BABYLON) {
  20145. var RenderingGroup = /** @class */ (function () {
  20146. /**
  20147. * Creates a new rendering group.
  20148. * @param index The rendering group index
  20149. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20150. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20151. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20152. */
  20153. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20154. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20155. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20156. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20157. this.index = index;
  20158. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20159. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20160. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20161. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20162. this._particleSystems = new BABYLON.SmartArray(256);
  20163. this._spriteManagers = new BABYLON.SmartArray(256);
  20164. this._edgesRenderers = new BABYLON.SmartArray(16);
  20165. this._scene = scene;
  20166. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20167. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20168. this.transparentSortCompareFn = transparentSortCompareFn;
  20169. }
  20170. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20171. /**
  20172. * Set the opaque sort comparison function.
  20173. * If null the sub meshes will be render in the order they were created
  20174. */
  20175. set: function (value) {
  20176. this._opaqueSortCompareFn = value;
  20177. if (value) {
  20178. this._renderOpaque = this.renderOpaqueSorted;
  20179. }
  20180. else {
  20181. this._renderOpaque = RenderingGroup.renderUnsorted;
  20182. }
  20183. },
  20184. enumerable: true,
  20185. configurable: true
  20186. });
  20187. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20188. /**
  20189. * Set the alpha test sort comparison function.
  20190. * If null the sub meshes will be render in the order they were created
  20191. */
  20192. set: function (value) {
  20193. this._alphaTestSortCompareFn = value;
  20194. if (value) {
  20195. this._renderAlphaTest = this.renderAlphaTestSorted;
  20196. }
  20197. else {
  20198. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20199. }
  20200. },
  20201. enumerable: true,
  20202. configurable: true
  20203. });
  20204. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20205. /**
  20206. * Set the transparent sort comparison function.
  20207. * If null the sub meshes will be render in the order they were created
  20208. */
  20209. set: function (value) {
  20210. if (value) {
  20211. this._transparentSortCompareFn = value;
  20212. }
  20213. else {
  20214. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20215. }
  20216. this._renderTransparent = this.renderTransparentSorted;
  20217. },
  20218. enumerable: true,
  20219. configurable: true
  20220. });
  20221. /**
  20222. * Render all the sub meshes contained in the group.
  20223. * @param customRenderFunction Used to override the default render behaviour of the group.
  20224. * @returns true if rendered some submeshes.
  20225. */
  20226. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20227. if (customRenderFunction) {
  20228. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20229. return;
  20230. }
  20231. var engine = this._scene.getEngine();
  20232. // Depth only
  20233. if (this._depthOnlySubMeshes.length !== 0) {
  20234. engine.setColorWrite(false);
  20235. this._renderAlphaTest(this._depthOnlySubMeshes);
  20236. engine.setColorWrite(true);
  20237. }
  20238. // Opaque
  20239. if (this._opaqueSubMeshes.length !== 0) {
  20240. this._renderOpaque(this._opaqueSubMeshes);
  20241. }
  20242. // Alpha test
  20243. if (this._alphaTestSubMeshes.length !== 0) {
  20244. this._renderAlphaTest(this._alphaTestSubMeshes);
  20245. }
  20246. var stencilState = engine.getStencilBuffer();
  20247. engine.setStencilBuffer(false);
  20248. // Sprites
  20249. if (renderSprites) {
  20250. this._renderSprites();
  20251. }
  20252. // Particles
  20253. if (renderParticles) {
  20254. this._renderParticles(activeMeshes);
  20255. }
  20256. if (this.onBeforeTransparentRendering) {
  20257. this.onBeforeTransparentRendering();
  20258. }
  20259. // Transparent
  20260. if (this._transparentSubMeshes.length !== 0) {
  20261. this._renderTransparent(this._transparentSubMeshes);
  20262. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20263. }
  20264. // Set back stencil to false in case it changes before the edge renderer.
  20265. engine.setStencilBuffer(false);
  20266. // Edges
  20267. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20268. this._edgesRenderers.data[edgesRendererIndex].render();
  20269. }
  20270. // Restore Stencil state.
  20271. engine.setStencilBuffer(stencilState);
  20272. };
  20273. /**
  20274. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20275. * @param subMeshes The submeshes to render
  20276. */
  20277. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20278. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20279. };
  20280. /**
  20281. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20282. * @param subMeshes The submeshes to render
  20283. */
  20284. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20285. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20286. };
  20287. /**
  20288. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20289. * @param subMeshes The submeshes to render
  20290. */
  20291. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20292. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20293. };
  20294. /**
  20295. * Renders the submeshes in a specified order.
  20296. * @param subMeshes The submeshes to sort before render
  20297. * @param sortCompareFn The comparison function use to sort
  20298. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  20299. * @param transparent Specifies to activate blending if true
  20300. */
  20301. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  20302. var subIndex = 0;
  20303. var subMesh;
  20304. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  20305. for (; subIndex < subMeshes.length; subIndex++) {
  20306. subMesh = subMeshes.data[subIndex];
  20307. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  20308. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  20309. }
  20310. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  20311. if (sortCompareFn) {
  20312. sortedArray.sort(sortCompareFn);
  20313. }
  20314. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  20315. subMesh = sortedArray[subIndex];
  20316. if (transparent) {
  20317. var material = subMesh.getMaterial();
  20318. if (material && material.needDepthPrePass) {
  20319. var engine = material.getScene().getEngine();
  20320. engine.setColorWrite(false);
  20321. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20322. subMesh.render(false);
  20323. engine.setColorWrite(true);
  20324. }
  20325. }
  20326. subMesh.render(transparent);
  20327. }
  20328. };
  20329. /**
  20330. * Renders the submeshes in the order they were dispatched (no sort applied).
  20331. * @param subMeshes The submeshes to render
  20332. */
  20333. RenderingGroup.renderUnsorted = function (subMeshes) {
  20334. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  20335. var submesh = subMeshes.data[subIndex];
  20336. submesh.render(false);
  20337. }
  20338. };
  20339. /**
  20340. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20341. * are rendered back to front if in the same alpha index.
  20342. *
  20343. * @param a The first submesh
  20344. * @param b The second submesh
  20345. * @returns The result of the comparison
  20346. */
  20347. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  20348. // Alpha index first
  20349. if (a._alphaIndex > b._alphaIndex) {
  20350. return 1;
  20351. }
  20352. if (a._alphaIndex < b._alphaIndex) {
  20353. return -1;
  20354. }
  20355. // Then distance to camera
  20356. return RenderingGroup.backToFrontSortCompare(a, b);
  20357. };
  20358. /**
  20359. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20360. * are rendered back to front.
  20361. *
  20362. * @param a The first submesh
  20363. * @param b The second submesh
  20364. * @returns The result of the comparison
  20365. */
  20366. RenderingGroup.backToFrontSortCompare = function (a, b) {
  20367. // Then distance to camera
  20368. if (a._distanceToCamera < b._distanceToCamera) {
  20369. return 1;
  20370. }
  20371. if (a._distanceToCamera > b._distanceToCamera) {
  20372. return -1;
  20373. }
  20374. return 0;
  20375. };
  20376. /**
  20377. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20378. * are rendered front to back (prevent overdraw).
  20379. *
  20380. * @param a The first submesh
  20381. * @param b The second submesh
  20382. * @returns The result of the comparison
  20383. */
  20384. RenderingGroup.frontToBackSortCompare = function (a, b) {
  20385. // Then distance to camera
  20386. if (a._distanceToCamera < b._distanceToCamera) {
  20387. return -1;
  20388. }
  20389. if (a._distanceToCamera > b._distanceToCamera) {
  20390. return 1;
  20391. }
  20392. return 0;
  20393. };
  20394. /**
  20395. * Resets the different lists of submeshes to prepare a new frame.
  20396. */
  20397. RenderingGroup.prototype.prepare = function () {
  20398. this._opaqueSubMeshes.reset();
  20399. this._transparentSubMeshes.reset();
  20400. this._alphaTestSubMeshes.reset();
  20401. this._depthOnlySubMeshes.reset();
  20402. this._particleSystems.reset();
  20403. this._spriteManagers.reset();
  20404. this._edgesRenderers.reset();
  20405. };
  20406. RenderingGroup.prototype.dispose = function () {
  20407. this._opaqueSubMeshes.dispose();
  20408. this._transparentSubMeshes.dispose();
  20409. this._alphaTestSubMeshes.dispose();
  20410. this._depthOnlySubMeshes.dispose();
  20411. this._particleSystems.dispose();
  20412. this._spriteManagers.dispose();
  20413. this._edgesRenderers.dispose();
  20414. };
  20415. /**
  20416. * Inserts the submesh in its correct queue depending on its material.
  20417. * @param subMesh The submesh to dispatch
  20418. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20419. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20420. */
  20421. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  20422. // Get mesh and materials if not provided
  20423. if (mesh === undefined) {
  20424. mesh = subMesh.getMesh();
  20425. }
  20426. if (material === undefined) {
  20427. material = subMesh.getMaterial();
  20428. }
  20429. if (material === null || material === undefined) {
  20430. return;
  20431. }
  20432. if (material.needAlphaBlendingForMesh(mesh)) {
  20433. this._transparentSubMeshes.push(subMesh);
  20434. }
  20435. else if (material.needAlphaTesting()) {
  20436. if (material.needDepthPrePass) {
  20437. this._depthOnlySubMeshes.push(subMesh);
  20438. }
  20439. this._alphaTestSubMeshes.push(subMesh);
  20440. }
  20441. else {
  20442. if (material.needDepthPrePass) {
  20443. this._depthOnlySubMeshes.push(subMesh);
  20444. }
  20445. this._opaqueSubMeshes.push(subMesh); // Opaque
  20446. }
  20447. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  20448. this._edgesRenderers.push(mesh._edgesRenderer);
  20449. }
  20450. };
  20451. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  20452. this._spriteManagers.push(spriteManager);
  20453. };
  20454. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  20455. this._particleSystems.push(particleSystem);
  20456. };
  20457. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  20458. if (this._particleSystems.length === 0) {
  20459. return;
  20460. }
  20461. // Particles
  20462. var activeCamera = this._scene.activeCamera;
  20463. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  20464. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  20465. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  20466. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  20467. continue;
  20468. }
  20469. var emitter = particleSystem.emitter;
  20470. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  20471. this._scene._activeParticles.addCount(particleSystem.render(), false);
  20472. }
  20473. }
  20474. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  20475. };
  20476. RenderingGroup.prototype._renderSprites = function () {
  20477. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  20478. return;
  20479. }
  20480. // Sprites
  20481. var activeCamera = this._scene.activeCamera;
  20482. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  20483. for (var id = 0; id < this._spriteManagers.length; id++) {
  20484. var spriteManager = this._spriteManagers.data[id];
  20485. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  20486. spriteManager.render();
  20487. }
  20488. }
  20489. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  20490. };
  20491. return RenderingGroup;
  20492. }());
  20493. BABYLON.RenderingGroup = RenderingGroup;
  20494. })(BABYLON || (BABYLON = {}));
  20495. //# sourceMappingURL=babylon.renderingGroup.js.map
  20496. var BABYLON;
  20497. (function (BABYLON) {
  20498. var ClickInfo = /** @class */ (function () {
  20499. function ClickInfo() {
  20500. this._singleClick = false;
  20501. this._doubleClick = false;
  20502. this._hasSwiped = false;
  20503. this._ignore = false;
  20504. }
  20505. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  20506. get: function () {
  20507. return this._singleClick;
  20508. },
  20509. set: function (b) {
  20510. this._singleClick = b;
  20511. },
  20512. enumerable: true,
  20513. configurable: true
  20514. });
  20515. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  20516. get: function () {
  20517. return this._doubleClick;
  20518. },
  20519. set: function (b) {
  20520. this._doubleClick = b;
  20521. },
  20522. enumerable: true,
  20523. configurable: true
  20524. });
  20525. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  20526. get: function () {
  20527. return this._hasSwiped;
  20528. },
  20529. set: function (b) {
  20530. this._hasSwiped = b;
  20531. },
  20532. enumerable: true,
  20533. configurable: true
  20534. });
  20535. Object.defineProperty(ClickInfo.prototype, "ignore", {
  20536. get: function () {
  20537. return this._ignore;
  20538. },
  20539. set: function (b) {
  20540. this._ignore = b;
  20541. },
  20542. enumerable: true,
  20543. configurable: true
  20544. });
  20545. return ClickInfo;
  20546. }());
  20547. /**
  20548. * This class is used by the onRenderingGroupObservable
  20549. */
  20550. var RenderingGroupInfo = /** @class */ (function () {
  20551. function RenderingGroupInfo() {
  20552. }
  20553. /**
  20554. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  20555. * This stage will be fired no matter what
  20556. */
  20557. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  20558. /**
  20559. * Called before opaque object are rendered.
  20560. * This stage will be fired only if there's 3D Opaque content to render
  20561. */
  20562. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  20563. /**
  20564. * Called after the opaque objects are rendered and before the transparent ones
  20565. * This stage will be fired only if there's 3D transparent content to render
  20566. */
  20567. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  20568. /**
  20569. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  20570. * This stage will be fired no matter what
  20571. */
  20572. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  20573. return RenderingGroupInfo;
  20574. }());
  20575. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  20576. /**
  20577. * Represents a scene to be rendered by the engine.
  20578. * @see http://doc.babylonjs.com/page.php?p=21911
  20579. */
  20580. var Scene = /** @class */ (function () {
  20581. /**
  20582. * @constructor
  20583. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  20584. */
  20585. function Scene(engine) {
  20586. // Members
  20587. this.autoClear = true;
  20588. this.autoClearDepthAndStencil = true;
  20589. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  20590. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  20591. this.forceWireframe = false;
  20592. this._forcePointsCloud = false;
  20593. this.forceShowBoundingBoxes = false;
  20594. this.animationsEnabled = true;
  20595. this.useConstantAnimationDeltaTime = false;
  20596. this.constantlyUpdateMeshUnderPointer = false;
  20597. this.hoverCursor = "pointer";
  20598. this.defaultCursor = "";
  20599. /**
  20600. * This is used to call preventDefault() on pointer down
  20601. * in order to block unwanted artifacts like system double clicks
  20602. */
  20603. this.preventDefaultOnPointerDown = true;
  20604. // Metadata
  20605. this.metadata = null;
  20606. /**
  20607. * An event triggered when the scene is disposed.
  20608. * @type {BABYLON.Observable}
  20609. */
  20610. this.onDisposeObservable = new BABYLON.Observable();
  20611. /**
  20612. * An event triggered before rendering the scene (right after animations and physics)
  20613. * @type {BABYLON.Observable}
  20614. */
  20615. this.onBeforeRenderObservable = new BABYLON.Observable();
  20616. /**
  20617. * An event triggered after rendering the scene
  20618. * @type {BABYLON.Observable}
  20619. */
  20620. this.onAfterRenderObservable = new BABYLON.Observable();
  20621. /**
  20622. * An event triggered before animating the scene
  20623. * @type {BABYLON.Observable}
  20624. */
  20625. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  20626. /**
  20627. * An event triggered after animations processing
  20628. * @type {BABYLON.Observable}
  20629. */
  20630. this.onAfterAnimationsObservable = new BABYLON.Observable();
  20631. /**
  20632. * An event triggered before draw calls are ready to be sent
  20633. * @type {BABYLON.Observable}
  20634. */
  20635. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  20636. /**
  20637. * An event triggered after draw calls have been sent
  20638. * @type {BABYLON.Observable}
  20639. */
  20640. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  20641. /**
  20642. * An event triggered when physic simulation is about to be run
  20643. * @type {BABYLON.Observable}
  20644. */
  20645. this.onBeforePhysicsObservable = new BABYLON.Observable();
  20646. /**
  20647. * An event triggered when physic simulation has been done
  20648. * @type {BABYLON.Observable}
  20649. */
  20650. this.onAfterPhysicsObservable = new BABYLON.Observable();
  20651. /**
  20652. * An event triggered when the scene is ready
  20653. * @type {BABYLON.Observable}
  20654. */
  20655. this.onReadyObservable = new BABYLON.Observable();
  20656. /**
  20657. * An event triggered before rendering a camera
  20658. * @type {BABYLON.Observable}
  20659. */
  20660. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  20661. /**
  20662. * An event triggered after rendering a camera
  20663. * @type {BABYLON.Observable}
  20664. */
  20665. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  20666. /**
  20667. * An event triggered when active meshes evaluation is about to start
  20668. * @type {BABYLON.Observable}
  20669. */
  20670. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20671. /**
  20672. * An event triggered when active meshes evaluation is done
  20673. * @type {BABYLON.Observable}
  20674. */
  20675. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20676. /**
  20677. * An event triggered when particles rendering is about to start
  20678. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20679. * @type {BABYLON.Observable}
  20680. */
  20681. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  20682. /**
  20683. * An event triggered when particles rendering is done
  20684. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20685. * @type {BABYLON.Observable}
  20686. */
  20687. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  20688. /**
  20689. * An event triggered when sprites rendering is about to start
  20690. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20691. * @type {BABYLON.Observable}
  20692. */
  20693. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  20694. /**
  20695. * An event triggered when sprites rendering is done
  20696. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20697. * @type {BABYLON.Observable}
  20698. */
  20699. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  20700. /**
  20701. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  20702. * @type {BABYLON.Observable}
  20703. */
  20704. this.onDataLoadedObservable = new BABYLON.Observable();
  20705. /**
  20706. * An event triggered when a camera is created
  20707. * @type {BABYLON.Observable}
  20708. */
  20709. this.onNewCameraAddedObservable = new BABYLON.Observable();
  20710. /**
  20711. * An event triggered when a camera is removed
  20712. * @type {BABYLON.Observable}
  20713. */
  20714. this.onCameraRemovedObservable = new BABYLON.Observable();
  20715. /**
  20716. * An event triggered when a light is created
  20717. * @type {BABYLON.Observable}
  20718. */
  20719. this.onNewLightAddedObservable = new BABYLON.Observable();
  20720. /**
  20721. * An event triggered when a light is removed
  20722. * @type {BABYLON.Observable}
  20723. */
  20724. this.onLightRemovedObservable = new BABYLON.Observable();
  20725. /**
  20726. * An event triggered when a geometry is created
  20727. * @type {BABYLON.Observable}
  20728. */
  20729. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  20730. /**
  20731. * An event triggered when a geometry is removed
  20732. * @type {BABYLON.Observable}
  20733. */
  20734. this.onGeometryRemovedObservable = new BABYLON.Observable();
  20735. /**
  20736. * An event triggered when a transform node is created
  20737. * @type {BABYLON.Observable}
  20738. */
  20739. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  20740. /**
  20741. * An event triggered when a transform node is removed
  20742. * @type {BABYLON.Observable}
  20743. */
  20744. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  20745. /**
  20746. * An event triggered when a mesh is created
  20747. * @type {BABYLON.Observable}
  20748. */
  20749. this.onNewMeshAddedObservable = new BABYLON.Observable();
  20750. /**
  20751. * An event triggered when a mesh is removed
  20752. * @type {BABYLON.Observable}
  20753. */
  20754. this.onMeshRemovedObservable = new BABYLON.Observable();
  20755. /**
  20756. * An event triggered when render targets are about to be rendered
  20757. * Can happen multiple times per frame.
  20758. * @type {BABYLON.Observable}
  20759. */
  20760. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  20761. /**
  20762. * An event triggered when render targets were rendered.
  20763. * Can happen multiple times per frame.
  20764. * @type {BABYLON.Observable}
  20765. */
  20766. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  20767. /**
  20768. * An event triggered before calculating deterministic simulation step
  20769. * @type {BABYLON.Observable}
  20770. */
  20771. this.onBeforeStepObservable = new BABYLON.Observable();
  20772. /**
  20773. * An event triggered after calculating deterministic simulation step
  20774. * @type {BABYLON.Observable}
  20775. */
  20776. this.onAfterStepObservable = new BABYLON.Observable();
  20777. /**
  20778. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  20779. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  20780. * 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)
  20781. */
  20782. this.onRenderingGroupObservable = new BABYLON.Observable();
  20783. // Animations
  20784. this.animations = [];
  20785. /**
  20786. * 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).
  20787. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  20788. */
  20789. this.onPrePointerObservable = new BABYLON.Observable();
  20790. /**
  20791. * Observable event triggered each time an input event is received from the rendering canvas
  20792. */
  20793. this.onPointerObservable = new BABYLON.Observable();
  20794. this._meshPickProceed = false;
  20795. this._currentPickResult = null;
  20796. this._previousPickResult = null;
  20797. this._totalPointersPressed = 0;
  20798. this._doubleClickOccured = false;
  20799. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  20800. this.cameraToUseForPointers = null;
  20801. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  20802. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  20803. this._startingPointerTime = 0;
  20804. this._previousStartingPointerTime = 0;
  20805. // Deterministic lockstep
  20806. this._timeAccumulator = 0;
  20807. this._currentStepId = 0;
  20808. this._currentInternalStep = 0;
  20809. // Keyboard
  20810. /**
  20811. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  20812. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  20813. */
  20814. this.onPreKeyboardObservable = new BABYLON.Observable();
  20815. /**
  20816. * Observable event triggered each time an keyboard event is received from the hosting window
  20817. */
  20818. this.onKeyboardObservable = new BABYLON.Observable();
  20819. // Coordinate system
  20820. /**
  20821. * use right-handed coordinate system on this scene.
  20822. * @type {boolean}
  20823. */
  20824. this._useRightHandedSystem = false;
  20825. // Fog
  20826. this._fogEnabled = true;
  20827. this._fogMode = Scene.FOGMODE_NONE;
  20828. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  20829. this.fogDensity = 0.1;
  20830. this.fogStart = 0;
  20831. this.fogEnd = 1000.0;
  20832. // Lights
  20833. /**
  20834. * is shadow enabled on this scene.
  20835. * @type {boolean}
  20836. */
  20837. this._shadowsEnabled = true;
  20838. /**
  20839. * is light enabled on this scene.
  20840. * @type {boolean}
  20841. */
  20842. this._lightsEnabled = true;
  20843. /**
  20844. * All of the lights added to this scene.
  20845. * @see BABYLON.Light
  20846. * @type {BABYLON.Light[]}
  20847. */
  20848. this.lights = new Array();
  20849. // Cameras
  20850. /** All of the cameras added to this scene. */
  20851. this.cameras = new Array();
  20852. /** All of the active cameras added to this scene. */
  20853. this.activeCameras = new Array();
  20854. // Meshes
  20855. /**
  20856. * All of the tranform nodes added to this scene.
  20857. * @see BABYLON.TransformNode
  20858. * @type {BABYLON.TransformNode[]}
  20859. */
  20860. this.transformNodes = new Array();
  20861. /**
  20862. * All of the (abstract) meshes added to this scene.
  20863. * @see BABYLON.AbstractMesh
  20864. * @type {BABYLON.AbstractMesh[]}
  20865. */
  20866. this.meshes = new Array();
  20867. /**
  20868. * All of the animation groups added to this scene.
  20869. * @see BABYLON.AnimationGroup
  20870. * @type {BABYLON.AnimationGroup[]}
  20871. */
  20872. this.animationGroups = new Array();
  20873. // Geometries
  20874. this._geometries = new Array();
  20875. this.materials = new Array();
  20876. this.multiMaterials = new Array();
  20877. // Textures
  20878. this._texturesEnabled = true;
  20879. this.textures = new Array();
  20880. // Particles
  20881. this.particlesEnabled = true;
  20882. this.particleSystems = new Array();
  20883. // Sprites
  20884. this.spritesEnabled = true;
  20885. this.spriteManagers = new Array();
  20886. // Layers
  20887. this.layers = new Array();
  20888. this.highlightLayers = new Array();
  20889. // Skeletons
  20890. this._skeletonsEnabled = true;
  20891. this.skeletons = new Array();
  20892. // Morph targets
  20893. this.morphTargetManagers = new Array();
  20894. // Lens flares
  20895. this.lensFlaresEnabled = true;
  20896. this.lensFlareSystems = new Array();
  20897. // Collisions
  20898. this.collisionsEnabled = true;
  20899. /** Defines the gravity applied to this scene */
  20900. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  20901. // Postprocesses
  20902. this.postProcesses = new Array();
  20903. this.postProcessesEnabled = true;
  20904. // Customs render targets
  20905. this.renderTargetsEnabled = true;
  20906. this.dumpNextRenderTargets = false;
  20907. this.customRenderTargets = new Array();
  20908. // Imported meshes
  20909. this.importedMeshesFiles = new Array();
  20910. // Probes
  20911. this.probesEnabled = true;
  20912. this.reflectionProbes = new Array();
  20913. this._actionManagers = new Array();
  20914. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  20915. // Procedural textures
  20916. this.proceduralTexturesEnabled = true;
  20917. this._proceduralTextures = new Array();
  20918. this.soundTracks = new Array();
  20919. this._audioEnabled = true;
  20920. this._headphone = false;
  20921. // Performance counters
  20922. this._totalVertices = new BABYLON.PerfCounter();
  20923. this._activeIndices = new BABYLON.PerfCounter();
  20924. this._activeParticles = new BABYLON.PerfCounter();
  20925. this._activeBones = new BABYLON.PerfCounter();
  20926. this._animationTime = 0;
  20927. this.animationTimeScale = 1;
  20928. this._renderId = 0;
  20929. this._executeWhenReadyTimeoutId = -1;
  20930. this._intermediateRendering = false;
  20931. this._viewUpdateFlag = -1;
  20932. this._projectionUpdateFlag = -1;
  20933. this._alternateViewUpdateFlag = -1;
  20934. this._alternateProjectionUpdateFlag = -1;
  20935. this._toBeDisposed = new BABYLON.SmartArray(256);
  20936. this._activeRequests = new Array();
  20937. this._pendingData = new Array();
  20938. this._isDisposed = false;
  20939. this.dispatchAllSubMeshesOfActiveMeshes = false;
  20940. this._activeMeshes = new BABYLON.SmartArray(256);
  20941. this._processedMaterials = new BABYLON.SmartArray(256);
  20942. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  20943. this._activeParticleSystems = new BABYLON.SmartArray(256);
  20944. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  20945. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  20946. this._activeAnimatables = new Array();
  20947. this._transformMatrix = BABYLON.Matrix.Zero();
  20948. this._useAlternateCameraConfiguration = false;
  20949. this._alternateRendering = false;
  20950. this.requireLightSorting = false;
  20951. this._activeMeshesFrozen = false;
  20952. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  20953. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  20954. this._engine.scenes.push(this);
  20955. this._uid = null;
  20956. this._renderingManager = new BABYLON.RenderingManager(this);
  20957. this.postProcessManager = new BABYLON.PostProcessManager(this);
  20958. if (BABYLON.OutlineRenderer) {
  20959. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  20960. }
  20961. if (BABYLON.Tools.IsWindowObjectExist()) {
  20962. this.attachControl();
  20963. }
  20964. //simplification queue
  20965. if (BABYLON.SimplificationQueue) {
  20966. this.simplificationQueue = new BABYLON.SimplificationQueue();
  20967. }
  20968. //collision coordinator initialization. For now legacy per default.
  20969. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  20970. // Uniform Buffer
  20971. this._createUbo();
  20972. // Default Image processing definition.
  20973. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  20974. }
  20975. Object.defineProperty(Scene, "FOGMODE_NONE", {
  20976. /** The fog is deactivated */
  20977. get: function () {
  20978. return Scene._FOGMODE_NONE;
  20979. },
  20980. enumerable: true,
  20981. configurable: true
  20982. });
  20983. Object.defineProperty(Scene, "FOGMODE_EXP", {
  20984. /** The fog density is following an exponential function */
  20985. get: function () {
  20986. return Scene._FOGMODE_EXP;
  20987. },
  20988. enumerable: true,
  20989. configurable: true
  20990. });
  20991. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  20992. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  20993. get: function () {
  20994. return Scene._FOGMODE_EXP2;
  20995. },
  20996. enumerable: true,
  20997. configurable: true
  20998. });
  20999. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21000. /** The fog density is following a linear function. */
  21001. get: function () {
  21002. return Scene._FOGMODE_LINEAR;
  21003. },
  21004. enumerable: true,
  21005. configurable: true
  21006. });
  21007. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21008. /**
  21009. * Texture used in all pbr material as the reflection texture.
  21010. * As in the majority of the scene they are the same (exception for multi room and so on),
  21011. * this is easier to reference from here than from all the materials.
  21012. */
  21013. get: function () {
  21014. return this._environmentTexture;
  21015. },
  21016. /**
  21017. * Texture used in all pbr material as the reflection texture.
  21018. * As in the majority of the scene they are the same (exception for multi room and so on),
  21019. * this is easier to set here than in all the materials.
  21020. */
  21021. set: function (value) {
  21022. if (this._environmentTexture === value) {
  21023. return;
  21024. }
  21025. this._environmentTexture = value;
  21026. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21027. },
  21028. enumerable: true,
  21029. configurable: true
  21030. });
  21031. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21032. /**
  21033. * Default image processing configuration used either in the rendering
  21034. * Forward main pass or through the imageProcessingPostProcess if present.
  21035. * As in the majority of the scene they are the same (exception for multi camera),
  21036. * this is easier to reference from here than from all the materials and post process.
  21037. *
  21038. * No setter as we it is a shared configuration, you can set the values instead.
  21039. */
  21040. get: function () {
  21041. return this._imageProcessingConfiguration;
  21042. },
  21043. enumerable: true,
  21044. configurable: true
  21045. });
  21046. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21047. get: function () {
  21048. return this._forcePointsCloud;
  21049. },
  21050. set: function (value) {
  21051. if (this._forcePointsCloud === value) {
  21052. return;
  21053. }
  21054. this._forcePointsCloud = value;
  21055. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21056. },
  21057. enumerable: true,
  21058. configurable: true
  21059. });
  21060. Object.defineProperty(Scene.prototype, "onDispose", {
  21061. /** A function to be executed when this scene is disposed. */
  21062. set: function (callback) {
  21063. if (this._onDisposeObserver) {
  21064. this.onDisposeObservable.remove(this._onDisposeObserver);
  21065. }
  21066. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21067. },
  21068. enumerable: true,
  21069. configurable: true
  21070. });
  21071. Object.defineProperty(Scene.prototype, "beforeRender", {
  21072. /** A function to be executed before rendering this scene */
  21073. set: function (callback) {
  21074. if (this._onBeforeRenderObserver) {
  21075. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21076. }
  21077. if (callback) {
  21078. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21079. }
  21080. },
  21081. enumerable: true,
  21082. configurable: true
  21083. });
  21084. Object.defineProperty(Scene.prototype, "afterRender", {
  21085. /** A function to be executed after rendering this scene */
  21086. set: function (callback) {
  21087. if (this._onAfterRenderObserver) {
  21088. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21089. }
  21090. if (callback) {
  21091. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21092. }
  21093. },
  21094. enumerable: true,
  21095. configurable: true
  21096. });
  21097. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21098. set: function (callback) {
  21099. if (this._onBeforeCameraRenderObserver) {
  21100. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21101. }
  21102. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21103. },
  21104. enumerable: true,
  21105. configurable: true
  21106. });
  21107. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21108. set: function (callback) {
  21109. if (this._onAfterCameraRenderObserver) {
  21110. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21111. }
  21112. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21113. },
  21114. enumerable: true,
  21115. configurable: true
  21116. });
  21117. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21118. get: function () {
  21119. if (!this._gamepadManager) {
  21120. this._gamepadManager = new BABYLON.GamepadManager(this);
  21121. }
  21122. return this._gamepadManager;
  21123. },
  21124. enumerable: true,
  21125. configurable: true
  21126. });
  21127. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21128. get: function () {
  21129. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21130. },
  21131. enumerable: true,
  21132. configurable: true
  21133. });
  21134. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21135. get: function () {
  21136. return this._useRightHandedSystem;
  21137. },
  21138. set: function (value) {
  21139. if (this._useRightHandedSystem === value) {
  21140. return;
  21141. }
  21142. this._useRightHandedSystem = value;
  21143. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21144. },
  21145. enumerable: true,
  21146. configurable: true
  21147. });
  21148. Scene.prototype.setStepId = function (newStepId) {
  21149. this._currentStepId = newStepId;
  21150. };
  21151. ;
  21152. Scene.prototype.getStepId = function () {
  21153. return this._currentStepId;
  21154. };
  21155. ;
  21156. Scene.prototype.getInternalStep = function () {
  21157. return this._currentInternalStep;
  21158. };
  21159. ;
  21160. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21161. get: function () {
  21162. return this._fogEnabled;
  21163. },
  21164. /**
  21165. * is fog enabled on this scene.
  21166. */
  21167. set: function (value) {
  21168. if (this._fogEnabled === value) {
  21169. return;
  21170. }
  21171. this._fogEnabled = value;
  21172. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21173. },
  21174. enumerable: true,
  21175. configurable: true
  21176. });
  21177. Object.defineProperty(Scene.prototype, "fogMode", {
  21178. get: function () {
  21179. return this._fogMode;
  21180. },
  21181. set: function (value) {
  21182. if (this._fogMode === value) {
  21183. return;
  21184. }
  21185. this._fogMode = value;
  21186. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21187. },
  21188. enumerable: true,
  21189. configurable: true
  21190. });
  21191. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21192. get: function () {
  21193. return this._shadowsEnabled;
  21194. },
  21195. set: function (value) {
  21196. if (this._shadowsEnabled === value) {
  21197. return;
  21198. }
  21199. this._shadowsEnabled = value;
  21200. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21201. },
  21202. enumerable: true,
  21203. configurable: true
  21204. });
  21205. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21206. get: function () {
  21207. return this._lightsEnabled;
  21208. },
  21209. set: function (value) {
  21210. if (this._lightsEnabled === value) {
  21211. return;
  21212. }
  21213. this._lightsEnabled = value;
  21214. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21215. },
  21216. enumerable: true,
  21217. configurable: true
  21218. });
  21219. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21220. /** The default material used on meshes when no material is affected */
  21221. get: function () {
  21222. if (!this._defaultMaterial) {
  21223. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21224. }
  21225. return this._defaultMaterial;
  21226. },
  21227. /** The default material used on meshes when no material is affected */
  21228. set: function (value) {
  21229. this._defaultMaterial = value;
  21230. },
  21231. enumerable: true,
  21232. configurable: true
  21233. });
  21234. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21235. get: function () {
  21236. return this._texturesEnabled;
  21237. },
  21238. set: function (value) {
  21239. if (this._texturesEnabled === value) {
  21240. return;
  21241. }
  21242. this._texturesEnabled = value;
  21243. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21244. },
  21245. enumerable: true,
  21246. configurable: true
  21247. });
  21248. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21249. get: function () {
  21250. return this._skeletonsEnabled;
  21251. },
  21252. set: function (value) {
  21253. if (this._skeletonsEnabled === value) {
  21254. return;
  21255. }
  21256. this._skeletonsEnabled = value;
  21257. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21258. },
  21259. enumerable: true,
  21260. configurable: true
  21261. });
  21262. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21263. get: function () {
  21264. if (!this._postProcessRenderPipelineManager) {
  21265. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21266. }
  21267. return this._postProcessRenderPipelineManager;
  21268. },
  21269. enumerable: true,
  21270. configurable: true
  21271. });
  21272. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21273. get: function () {
  21274. if (!this._mainSoundTrack) {
  21275. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21276. }
  21277. return this._mainSoundTrack;
  21278. },
  21279. enumerable: true,
  21280. configurable: true
  21281. });
  21282. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21283. get: function () {
  21284. return this._alternateRendering;
  21285. },
  21286. enumerable: true,
  21287. configurable: true
  21288. });
  21289. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  21290. get: function () {
  21291. return this._frustumPlanes;
  21292. },
  21293. enumerable: true,
  21294. configurable: true
  21295. });
  21296. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  21297. /**
  21298. * Gets the current geometry buffer associated to the scene.
  21299. */
  21300. get: function () {
  21301. return this._geometryBufferRenderer;
  21302. },
  21303. /**
  21304. * Sets the current geometry buffer for the scene.
  21305. */
  21306. set: function (geometryBufferRenderer) {
  21307. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  21308. this._geometryBufferRenderer = geometryBufferRenderer;
  21309. }
  21310. },
  21311. enumerable: true,
  21312. configurable: true
  21313. });
  21314. Object.defineProperty(Scene.prototype, "debugLayer", {
  21315. // Properties
  21316. get: function () {
  21317. if (!this._debugLayer) {
  21318. this._debugLayer = new BABYLON.DebugLayer(this);
  21319. }
  21320. return this._debugLayer;
  21321. },
  21322. enumerable: true,
  21323. configurable: true
  21324. });
  21325. Object.defineProperty(Scene.prototype, "workerCollisions", {
  21326. get: function () {
  21327. return this._workerCollisions;
  21328. },
  21329. set: function (enabled) {
  21330. if (!BABYLON.CollisionCoordinatorLegacy) {
  21331. return;
  21332. }
  21333. enabled = (enabled && !!Worker);
  21334. this._workerCollisions = enabled;
  21335. if (this.collisionCoordinator) {
  21336. this.collisionCoordinator.destroy();
  21337. }
  21338. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  21339. this.collisionCoordinator.init(this);
  21340. },
  21341. enumerable: true,
  21342. configurable: true
  21343. });
  21344. Object.defineProperty(Scene.prototype, "selectionOctree", {
  21345. get: function () {
  21346. return this._selectionOctree;
  21347. },
  21348. enumerable: true,
  21349. configurable: true
  21350. });
  21351. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  21352. /**
  21353. * The mesh that is currently under the pointer.
  21354. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  21355. */
  21356. get: function () {
  21357. return this._pointerOverMesh;
  21358. },
  21359. enumerable: true,
  21360. configurable: true
  21361. });
  21362. Object.defineProperty(Scene.prototype, "pointerX", {
  21363. /**
  21364. * Current on-screen X position of the pointer
  21365. * @return {number} X position of the pointer
  21366. */
  21367. get: function () {
  21368. return this._pointerX;
  21369. },
  21370. enumerable: true,
  21371. configurable: true
  21372. });
  21373. Object.defineProperty(Scene.prototype, "pointerY", {
  21374. /**
  21375. * Current on-screen Y position of the pointer
  21376. * @return {number} Y position of the pointer
  21377. */
  21378. get: function () {
  21379. return this._pointerY;
  21380. },
  21381. enumerable: true,
  21382. configurable: true
  21383. });
  21384. Scene.prototype.getCachedMaterial = function () {
  21385. return this._cachedMaterial;
  21386. };
  21387. Scene.prototype.getCachedEffect = function () {
  21388. return this._cachedEffect;
  21389. };
  21390. Scene.prototype.getCachedVisibility = function () {
  21391. return this._cachedVisibility;
  21392. };
  21393. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  21394. if (visibility === void 0) { visibility = 1; }
  21395. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  21396. };
  21397. Scene.prototype.getBoundingBoxRenderer = function () {
  21398. if (!this._boundingBoxRenderer) {
  21399. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  21400. }
  21401. return this._boundingBoxRenderer;
  21402. };
  21403. Scene.prototype.getOutlineRenderer = function () {
  21404. return this._outlineRenderer;
  21405. };
  21406. Scene.prototype.getEngine = function () {
  21407. return this._engine;
  21408. };
  21409. Scene.prototype.getTotalVertices = function () {
  21410. return this._totalVertices.current;
  21411. };
  21412. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  21413. get: function () {
  21414. return this._totalVertices;
  21415. },
  21416. enumerable: true,
  21417. configurable: true
  21418. });
  21419. Scene.prototype.getActiveIndices = function () {
  21420. return this._activeIndices.current;
  21421. };
  21422. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  21423. get: function () {
  21424. return this._activeIndices;
  21425. },
  21426. enumerable: true,
  21427. configurable: true
  21428. });
  21429. Scene.prototype.getActiveParticles = function () {
  21430. return this._activeParticles.current;
  21431. };
  21432. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  21433. get: function () {
  21434. return this._activeParticles;
  21435. },
  21436. enumerable: true,
  21437. configurable: true
  21438. });
  21439. Scene.prototype.getActiveBones = function () {
  21440. return this._activeBones.current;
  21441. };
  21442. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  21443. get: function () {
  21444. return this._activeBones;
  21445. },
  21446. enumerable: true,
  21447. configurable: true
  21448. });
  21449. // Stats
  21450. Scene.prototype.getInterFramePerfCounter = function () {
  21451. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21452. return 0;
  21453. };
  21454. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  21455. get: function () {
  21456. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21457. return null;
  21458. },
  21459. enumerable: true,
  21460. configurable: true
  21461. });
  21462. Scene.prototype.getLastFrameDuration = function () {
  21463. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  21464. return 0;
  21465. };
  21466. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  21467. get: function () {
  21468. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21469. return null;
  21470. },
  21471. enumerable: true,
  21472. configurable: true
  21473. });
  21474. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  21475. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  21476. return 0;
  21477. };
  21478. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  21479. get: function () {
  21480. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21481. return null;
  21482. },
  21483. enumerable: true,
  21484. configurable: true
  21485. });
  21486. Scene.prototype.getActiveMeshes = function () {
  21487. return this._activeMeshes;
  21488. };
  21489. Scene.prototype.getRenderTargetsDuration = function () {
  21490. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  21491. return 0;
  21492. };
  21493. Scene.prototype.getRenderDuration = function () {
  21494. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  21495. return 0;
  21496. };
  21497. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  21498. get: function () {
  21499. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21500. return null;
  21501. },
  21502. enumerable: true,
  21503. configurable: true
  21504. });
  21505. Scene.prototype.getParticlesDuration = function () {
  21506. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  21507. return 0;
  21508. };
  21509. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  21510. get: function () {
  21511. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21512. return null;
  21513. },
  21514. enumerable: true,
  21515. configurable: true
  21516. });
  21517. Scene.prototype.getSpritesDuration = function () {
  21518. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  21519. return 0;
  21520. };
  21521. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  21522. get: function () {
  21523. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  21524. return null;
  21525. },
  21526. enumerable: true,
  21527. configurable: true
  21528. });
  21529. Scene.prototype.getAnimationRatio = function () {
  21530. return this._animationRatio;
  21531. };
  21532. Scene.prototype.getRenderId = function () {
  21533. return this._renderId;
  21534. };
  21535. Scene.prototype.incrementRenderId = function () {
  21536. this._renderId++;
  21537. };
  21538. Scene.prototype._updatePointerPosition = function (evt) {
  21539. var canvasRect = this._engine.getRenderingCanvasClientRect();
  21540. if (!canvasRect) {
  21541. return;
  21542. }
  21543. this._pointerX = evt.clientX - canvasRect.left;
  21544. this._pointerY = evt.clientY - canvasRect.top;
  21545. this._unTranslatedPointerX = this._pointerX;
  21546. this._unTranslatedPointerY = this._pointerY;
  21547. };
  21548. Scene.prototype._createUbo = function () {
  21549. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21550. this._sceneUbo.addUniform("viewProjection", 16);
  21551. this._sceneUbo.addUniform("view", 16);
  21552. };
  21553. Scene.prototype._createAlternateUbo = function () {
  21554. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21555. this._alternateSceneUbo.addUniform("viewProjection", 16);
  21556. this._alternateSceneUbo.addUniform("view", 16);
  21557. };
  21558. // Pointers handling
  21559. /**
  21560. * Use this method to simulate a pointer move on a mesh
  21561. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21562. */
  21563. Scene.prototype.simulatePointerMove = function (pickResult) {
  21564. var evt = new PointerEvent("pointermove");
  21565. return this._processPointerMove(pickResult, evt);
  21566. };
  21567. Scene.prototype._processPointerMove = function (pickResult, evt) {
  21568. var canvas = this._engine.getRenderingCanvas();
  21569. if (!canvas) {
  21570. return this;
  21571. }
  21572. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21573. this.setPointerOverSprite(null);
  21574. this.setPointerOverMesh(pickResult.pickedMesh);
  21575. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  21576. if (this._pointerOverMesh.actionManager.hoverCursor) {
  21577. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  21578. }
  21579. else {
  21580. canvas.style.cursor = this.hoverCursor;
  21581. }
  21582. }
  21583. else {
  21584. canvas.style.cursor = this.defaultCursor;
  21585. }
  21586. }
  21587. else {
  21588. this.setPointerOverMesh(null);
  21589. // Sprites
  21590. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  21591. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  21592. this.setPointerOverSprite(pickResult.pickedSprite);
  21593. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  21594. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  21595. }
  21596. else {
  21597. canvas.style.cursor = this.hoverCursor;
  21598. }
  21599. }
  21600. else {
  21601. this.setPointerOverSprite(null);
  21602. // Restore pointer
  21603. canvas.style.cursor = this.defaultCursor;
  21604. }
  21605. }
  21606. if (pickResult) {
  21607. if (this.onPointerMove) {
  21608. this.onPointerMove(evt, pickResult);
  21609. }
  21610. if (this.onPointerObservable.hasObservers()) {
  21611. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21612. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21613. this.onPointerObservable.notifyObservers(pi, type);
  21614. }
  21615. }
  21616. return this;
  21617. };
  21618. /**
  21619. * Use this method to simulate a pointer down on a mesh
  21620. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21621. */
  21622. Scene.prototype.simulatePointerDown = function (pickResult) {
  21623. var evt = new PointerEvent("pointerdown");
  21624. return this._processPointerDown(pickResult, evt);
  21625. };
  21626. Scene.prototype._processPointerDown = function (pickResult, evt) {
  21627. var _this = this;
  21628. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21629. this._pickedDownMesh = pickResult.pickedMesh;
  21630. var actionManager = pickResult.pickedMesh.actionManager;
  21631. if (actionManager) {
  21632. if (actionManager.hasPickTriggers) {
  21633. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21634. switch (evt.button) {
  21635. case 0:
  21636. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21637. break;
  21638. case 1:
  21639. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21640. break;
  21641. case 2:
  21642. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21643. break;
  21644. }
  21645. }
  21646. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  21647. window.setTimeout(function () {
  21648. 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);
  21649. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  21650. if (_this._totalPointersPressed !== 0 &&
  21651. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  21652. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  21653. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  21654. _this._startingPointerTime = 0;
  21655. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21656. }
  21657. }
  21658. }, Scene.LongPressDelay);
  21659. }
  21660. }
  21661. }
  21662. if (pickResult) {
  21663. if (this.onPointerDown) {
  21664. this.onPointerDown(evt, pickResult);
  21665. }
  21666. if (this.onPointerObservable.hasObservers()) {
  21667. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21668. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21669. this.onPointerObservable.notifyObservers(pi, type);
  21670. }
  21671. }
  21672. return this;
  21673. };
  21674. /**
  21675. * Use this method to simulate a pointer up on a mesh
  21676. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21677. */
  21678. Scene.prototype.simulatePointerUp = function (pickResult) {
  21679. var evt = new PointerEvent("pointerup");
  21680. var clickInfo = new ClickInfo();
  21681. clickInfo.singleClick = true;
  21682. clickInfo.ignore = true;
  21683. return this._processPointerUp(pickResult, evt, clickInfo);
  21684. };
  21685. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  21686. if (pickResult && pickResult && pickResult.pickedMesh) {
  21687. this._pickedUpMesh = pickResult.pickedMesh;
  21688. if (this._pickedDownMesh === this._pickedUpMesh) {
  21689. if (this.onPointerPick) {
  21690. this.onPointerPick(evt, pickResult);
  21691. }
  21692. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  21693. var type = BABYLON.PointerEventTypes.POINTERPICK;
  21694. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21695. this.onPointerObservable.notifyObservers(pi, type);
  21696. }
  21697. }
  21698. if (pickResult.pickedMesh.actionManager) {
  21699. if (clickInfo.ignore) {
  21700. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21701. }
  21702. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  21703. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21704. }
  21705. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21706. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21707. }
  21708. }
  21709. }
  21710. if (this._pickedDownMesh &&
  21711. this._pickedDownMesh.actionManager &&
  21712. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  21713. this._pickedDownMesh !== this._pickedUpMesh) {
  21714. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  21715. }
  21716. if (this.onPointerUp) {
  21717. this.onPointerUp(evt, pickResult);
  21718. }
  21719. if (this.onPointerObservable.hasObservers()) {
  21720. if (!clickInfo.ignore) {
  21721. if (!clickInfo.hasSwiped) {
  21722. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  21723. var type = BABYLON.PointerEventTypes.POINTERTAP;
  21724. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21725. this.onPointerObservable.notifyObservers(pi, type);
  21726. }
  21727. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  21728. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  21729. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21730. this.onPointerObservable.notifyObservers(pi, type);
  21731. }
  21732. }
  21733. }
  21734. else {
  21735. var type = BABYLON.PointerEventTypes.POINTERUP;
  21736. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21737. this.onPointerObservable.notifyObservers(pi, type);
  21738. }
  21739. }
  21740. return this;
  21741. };
  21742. /**
  21743. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  21744. * @param attachUp defines if you want to attach events to pointerup
  21745. * @param attachDown defines if you want to attach events to pointerdown
  21746. * @param attachMove defines if you want to attach events to pointermove
  21747. */
  21748. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  21749. var _this = this;
  21750. if (attachUp === void 0) { attachUp = true; }
  21751. if (attachDown === void 0) { attachDown = true; }
  21752. if (attachMove === void 0) { attachMove = true; }
  21753. this._initActionManager = function (act, clickInfo) {
  21754. if (!_this._meshPickProceed) {
  21755. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21756. _this._currentPickResult = pickResult;
  21757. if (pickResult) {
  21758. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  21759. }
  21760. _this._meshPickProceed = true;
  21761. }
  21762. return act;
  21763. };
  21764. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  21765. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  21766. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  21767. btn !== _this._previousButtonPressed) {
  21768. _this._doubleClickOccured = false;
  21769. clickInfo.singleClick = true;
  21770. clickInfo.ignore = false;
  21771. cb(clickInfo, _this._currentPickResult);
  21772. }
  21773. };
  21774. this._initClickEvent = function (obs1, obs2, evt, cb) {
  21775. var clickInfo = new ClickInfo();
  21776. _this._currentPickResult = null;
  21777. var act = null;
  21778. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  21779. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  21780. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21781. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  21782. act = _this._initActionManager(act, clickInfo);
  21783. if (act)
  21784. checkPicking = act.hasPickTriggers;
  21785. }
  21786. if (checkPicking) {
  21787. var btn = evt.button;
  21788. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  21789. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  21790. if (!clickInfo.hasSwiped) {
  21791. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  21792. if (!checkSingleClickImmediately) {
  21793. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  21794. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21795. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21796. act = _this._initActionManager(act, clickInfo);
  21797. if (act)
  21798. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21799. }
  21800. }
  21801. if (checkSingleClickImmediately) {
  21802. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  21803. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  21804. btn !== _this._previousButtonPressed) {
  21805. clickInfo.singleClick = true;
  21806. cb(clickInfo, _this._currentPickResult);
  21807. }
  21808. }
  21809. else {
  21810. // wait that no double click has been raised during the double click delay
  21811. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21812. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  21813. }
  21814. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  21815. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21816. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21817. act = _this._initActionManager(act, clickInfo);
  21818. if (act)
  21819. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21820. }
  21821. if (checkDoubleClick) {
  21822. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  21823. if (btn === _this._previousButtonPressed &&
  21824. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  21825. !_this._doubleClickOccured) {
  21826. // pointer has not moved for 2 clicks, it's a double click
  21827. if (!clickInfo.hasSwiped &&
  21828. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  21829. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  21830. _this._previousStartingPointerTime = 0;
  21831. _this._doubleClickOccured = true;
  21832. clickInfo.doubleClick = true;
  21833. clickInfo.ignore = false;
  21834. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  21835. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  21836. }
  21837. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21838. cb(clickInfo, _this._currentPickResult);
  21839. }
  21840. else {
  21841. _this._doubleClickOccured = false;
  21842. _this._previousStartingPointerTime = _this._startingPointerTime;
  21843. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  21844. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  21845. _this._previousButtonPressed = btn;
  21846. if (Scene.ExclusiveDoubleClickMode) {
  21847. if (_this._previousDelayedSimpleClickTimeout) {
  21848. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  21849. }
  21850. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21851. cb(clickInfo, _this._previousPickResult);
  21852. }
  21853. else {
  21854. cb(clickInfo, _this._currentPickResult);
  21855. }
  21856. }
  21857. }
  21858. else {
  21859. _this._doubleClickOccured = false;
  21860. _this._previousStartingPointerTime = _this._startingPointerTime;
  21861. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  21862. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  21863. _this._previousButtonPressed = btn;
  21864. }
  21865. }
  21866. }
  21867. }
  21868. clickInfo.ignore = true;
  21869. cb(clickInfo, _this._currentPickResult);
  21870. };
  21871. this._spritePredicate = function (sprite) {
  21872. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  21873. };
  21874. this._onPointerMove = function (evt) {
  21875. _this._updatePointerPosition(evt);
  21876. // PreObservable support
  21877. if (_this.onPrePointerObservable.hasObservers()) {
  21878. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21879. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21880. _this.onPrePointerObservable.notifyObservers(pi, type);
  21881. if (pi.skipOnPointerObservable) {
  21882. return;
  21883. }
  21884. }
  21885. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21886. return;
  21887. }
  21888. if (!_this.pointerMovePredicate) {
  21889. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  21890. }
  21891. // Meshes
  21892. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  21893. _this._processPointerMove(pickResult, evt);
  21894. };
  21895. this._onPointerDown = function (evt) {
  21896. _this._totalPointersPressed++;
  21897. _this._pickedDownMesh = null;
  21898. _this._meshPickProceed = false;
  21899. _this._updatePointerPosition(evt);
  21900. if (_this.preventDefaultOnPointerDown && canvas) {
  21901. evt.preventDefault();
  21902. canvas.focus();
  21903. }
  21904. // PreObservable support
  21905. if (_this.onPrePointerObservable.hasObservers()) {
  21906. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21907. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21908. _this.onPrePointerObservable.notifyObservers(pi, type);
  21909. if (pi.skipOnPointerObservable) {
  21910. return;
  21911. }
  21912. }
  21913. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21914. return;
  21915. }
  21916. _this._startingPointerPosition.x = _this._pointerX;
  21917. _this._startingPointerPosition.y = _this._pointerY;
  21918. _this._startingPointerTime = new Date().getTime();
  21919. if (!_this.pointerDownPredicate) {
  21920. _this.pointerDownPredicate = function (mesh) {
  21921. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  21922. };
  21923. }
  21924. // Meshes
  21925. _this._pickedDownMesh = null;
  21926. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21927. _this._processPointerDown(pickResult, evt);
  21928. // Sprites
  21929. _this._pickedDownSprite = null;
  21930. if (_this.spriteManagers.length > 0) {
  21931. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  21932. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  21933. if (pickResult.pickedSprite.actionManager) {
  21934. _this._pickedDownSprite = pickResult.pickedSprite;
  21935. switch (evt.button) {
  21936. case 0:
  21937. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21938. break;
  21939. case 1:
  21940. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21941. break;
  21942. case 2:
  21943. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21944. break;
  21945. }
  21946. if (pickResult.pickedSprite.actionManager) {
  21947. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21948. }
  21949. }
  21950. }
  21951. }
  21952. };
  21953. this._onPointerUp = function (evt) {
  21954. if (_this._totalPointersPressed === 0) {
  21955. return; // So we need to test it the pointer down was pressed before.
  21956. }
  21957. _this._totalPointersPressed--;
  21958. _this._pickedUpMesh = null;
  21959. _this._meshPickProceed = false;
  21960. _this._updatePointerPosition(evt);
  21961. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  21962. // PreObservable support
  21963. if (_this.onPrePointerObservable.hasObservers()) {
  21964. if (!clickInfo.ignore) {
  21965. if (!clickInfo.hasSwiped) {
  21966. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  21967. var type = BABYLON.PointerEventTypes.POINTERTAP;
  21968. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21969. _this.onPrePointerObservable.notifyObservers(pi, type);
  21970. if (pi.skipOnPointerObservable) {
  21971. return;
  21972. }
  21973. }
  21974. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  21975. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  21976. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21977. _this.onPrePointerObservable.notifyObservers(pi, type);
  21978. if (pi.skipOnPointerObservable) {
  21979. return;
  21980. }
  21981. }
  21982. }
  21983. }
  21984. else {
  21985. var type = BABYLON.PointerEventTypes.POINTERUP;
  21986. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21987. _this.onPrePointerObservable.notifyObservers(pi, type);
  21988. if (pi.skipOnPointerObservable) {
  21989. return;
  21990. }
  21991. }
  21992. }
  21993. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21994. return;
  21995. }
  21996. if (!_this.pointerUpPredicate) {
  21997. _this.pointerUpPredicate = function (mesh) {
  21998. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  21999. };
  22000. }
  22001. // Meshes
  22002. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22003. _this._initActionManager(null, clickInfo);
  22004. }
  22005. if (!pickResult) {
  22006. pickResult = _this._currentPickResult;
  22007. }
  22008. _this._processPointerUp(pickResult, evt, clickInfo);
  22009. // Sprites
  22010. if (_this.spriteManagers.length > 0) {
  22011. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22012. if (spritePickResult) {
  22013. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22014. if (spritePickResult.pickedSprite.actionManager) {
  22015. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22016. if (spritePickResult.pickedSprite.actionManager) {
  22017. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22018. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22019. }
  22020. }
  22021. }
  22022. }
  22023. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22024. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22025. }
  22026. }
  22027. }
  22028. _this._previousPickResult = _this._currentPickResult;
  22029. });
  22030. };
  22031. this._onKeyDown = function (evt) {
  22032. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22033. if (_this.onPreKeyboardObservable.hasObservers()) {
  22034. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22035. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22036. if (pi.skipOnPointerObservable) {
  22037. return;
  22038. }
  22039. }
  22040. if (_this.onKeyboardObservable.hasObservers()) {
  22041. var pi = new BABYLON.KeyboardInfo(type, evt);
  22042. _this.onKeyboardObservable.notifyObservers(pi, type);
  22043. }
  22044. if (_this.actionManager) {
  22045. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22046. }
  22047. };
  22048. this._onKeyUp = function (evt) {
  22049. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22050. if (_this.onPreKeyboardObservable.hasObservers()) {
  22051. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22052. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22053. if (pi.skipOnPointerObservable) {
  22054. return;
  22055. }
  22056. }
  22057. if (_this.onKeyboardObservable.hasObservers()) {
  22058. var pi = new BABYLON.KeyboardInfo(type, evt);
  22059. _this.onKeyboardObservable.notifyObservers(pi, type);
  22060. }
  22061. if (_this.actionManager) {
  22062. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22063. }
  22064. };
  22065. var engine = this.getEngine();
  22066. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22067. if (!canvas) {
  22068. return;
  22069. }
  22070. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22071. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22072. });
  22073. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22074. if (!canvas) {
  22075. return;
  22076. }
  22077. canvas.removeEventListener("keydown", _this._onKeyDown);
  22078. canvas.removeEventListener("keyup", _this._onKeyUp);
  22079. });
  22080. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22081. var canvas = this._engine.getRenderingCanvas();
  22082. if (!canvas) {
  22083. return;
  22084. }
  22085. if (attachMove) {
  22086. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22087. // Wheel
  22088. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22089. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22090. }
  22091. if (attachDown) {
  22092. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22093. }
  22094. if (attachUp) {
  22095. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22096. }
  22097. canvas.tabIndex = 1;
  22098. };
  22099. Scene.prototype.detachControl = function () {
  22100. var engine = this.getEngine();
  22101. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22102. var canvas = engine.getRenderingCanvas();
  22103. if (!canvas) {
  22104. return;
  22105. }
  22106. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22107. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22108. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22109. if (this._onCanvasBlurObserver) {
  22110. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22111. }
  22112. if (this._onCanvasFocusObserver) {
  22113. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22114. }
  22115. // Wheel
  22116. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22117. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22118. // Keyboard
  22119. canvas.removeEventListener("keydown", this._onKeyDown);
  22120. canvas.removeEventListener("keyup", this._onKeyUp);
  22121. // Observables
  22122. this.onKeyboardObservable.clear();
  22123. this.onPreKeyboardObservable.clear();
  22124. this.onPointerObservable.clear();
  22125. this.onPrePointerObservable.clear();
  22126. };
  22127. /**
  22128. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22129. * Delay loaded resources are not taking in account
  22130. * @return true if all required resources are ready
  22131. */
  22132. Scene.prototype.isReady = function () {
  22133. if (this._isDisposed) {
  22134. return false;
  22135. }
  22136. if (this._pendingData.length > 0) {
  22137. return false;
  22138. }
  22139. var index;
  22140. var engine = this.getEngine();
  22141. // Geometries
  22142. for (index = 0; index < this._geometries.length; index++) {
  22143. var geometry = this._geometries[index];
  22144. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22145. return false;
  22146. }
  22147. }
  22148. // Meshes
  22149. for (index = 0; index < this.meshes.length; index++) {
  22150. var mesh = this.meshes[index];
  22151. if (!mesh.isEnabled()) {
  22152. continue;
  22153. }
  22154. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22155. continue;
  22156. }
  22157. if (!mesh.isReady()) {
  22158. return false;
  22159. }
  22160. // Highlight layers
  22161. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22162. for (var _i = 0, _a = this.highlightLayers; _i < _a.length; _i++) {
  22163. var layer = _a[_i];
  22164. if (!layer.hasMesh(mesh)) {
  22165. continue;
  22166. }
  22167. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22168. var subMesh = _c[_b];
  22169. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22170. return false;
  22171. }
  22172. }
  22173. }
  22174. }
  22175. return true;
  22176. };
  22177. Scene.prototype.resetCachedMaterial = function () {
  22178. this._cachedMaterial = null;
  22179. this._cachedEffect = null;
  22180. this._cachedVisibility = null;
  22181. };
  22182. Scene.prototype.registerBeforeRender = function (func) {
  22183. this.onBeforeRenderObservable.add(func);
  22184. };
  22185. Scene.prototype.unregisterBeforeRender = function (func) {
  22186. this.onBeforeRenderObservable.removeCallback(func);
  22187. };
  22188. Scene.prototype.registerAfterRender = function (func) {
  22189. this.onAfterRenderObservable.add(func);
  22190. };
  22191. Scene.prototype.unregisterAfterRender = function (func) {
  22192. this.onAfterRenderObservable.removeCallback(func);
  22193. };
  22194. Scene.prototype._executeOnceBeforeRender = function (func) {
  22195. var _this = this;
  22196. var execFunc = function () {
  22197. func();
  22198. setTimeout(function () {
  22199. _this.unregisterBeforeRender(execFunc);
  22200. });
  22201. };
  22202. this.registerBeforeRender(execFunc);
  22203. };
  22204. /**
  22205. * The provided function will run before render once and will be disposed afterwards.
  22206. * A timeout delay can be provided so that the function will be executed in N ms.
  22207. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22208. * @param func The function to be executed.
  22209. * @param timeout optional delay in ms
  22210. */
  22211. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22212. var _this = this;
  22213. if (timeout !== undefined) {
  22214. setTimeout(function () {
  22215. _this._executeOnceBeforeRender(func);
  22216. }, timeout);
  22217. }
  22218. else {
  22219. this._executeOnceBeforeRender(func);
  22220. }
  22221. };
  22222. Scene.prototype._addPendingData = function (data) {
  22223. this._pendingData.push(data);
  22224. };
  22225. Scene.prototype._removePendingData = function (data) {
  22226. var wasLoading = this.isLoading;
  22227. var index = this._pendingData.indexOf(data);
  22228. if (index !== -1) {
  22229. this._pendingData.splice(index, 1);
  22230. }
  22231. if (wasLoading && !this.isLoading) {
  22232. this.onDataLoadedObservable.notifyObservers(this);
  22233. }
  22234. };
  22235. Scene.prototype.getWaitingItemsCount = function () {
  22236. return this._pendingData.length;
  22237. };
  22238. Object.defineProperty(Scene.prototype, "isLoading", {
  22239. get: function () {
  22240. return this._pendingData.length > 0;
  22241. },
  22242. enumerable: true,
  22243. configurable: true
  22244. });
  22245. /**
  22246. * Registers a function to be executed when the scene is ready.
  22247. * @param {Function} func - the function to be executed.
  22248. */
  22249. Scene.prototype.executeWhenReady = function (func) {
  22250. var _this = this;
  22251. this.onReadyObservable.add(func);
  22252. if (this._executeWhenReadyTimeoutId !== -1) {
  22253. return;
  22254. }
  22255. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22256. _this._checkIsReady();
  22257. }, 150);
  22258. };
  22259. Scene.prototype._checkIsReady = function () {
  22260. var _this = this;
  22261. if (this.isReady()) {
  22262. this.onReadyObservable.notifyObservers(this);
  22263. this.onReadyObservable.clear();
  22264. this._executeWhenReadyTimeoutId = -1;
  22265. return;
  22266. }
  22267. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22268. _this._checkIsReady();
  22269. }, 150);
  22270. };
  22271. // Animations
  22272. /**
  22273. * Will start the animation sequence of a given target
  22274. * @param target - the target
  22275. * @param {number} from - from which frame should animation start
  22276. * @param {number} to - till which frame should animation run.
  22277. * @param {boolean} [loop] - should the animation loop
  22278. * @param {number} [speedRatio] - the speed in which to run the animation
  22279. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  22280. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  22281. * Returns {BABYLON.Animatable} the animatable object created for this animation
  22282. * See BABYLON.Animatable
  22283. */
  22284. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  22285. if (speedRatio === void 0) { speedRatio = 1.0; }
  22286. if (from > to && speedRatio > 0) {
  22287. speedRatio *= -1;
  22288. }
  22289. this.stopAnimation(target);
  22290. if (!animatable) {
  22291. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  22292. }
  22293. // Local animations
  22294. if (target.animations) {
  22295. animatable.appendAnimations(target, target.animations);
  22296. }
  22297. // Children animations
  22298. if (target.getAnimatables) {
  22299. var animatables = target.getAnimatables();
  22300. for (var index = 0; index < animatables.length; index++) {
  22301. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  22302. }
  22303. }
  22304. animatable.reset();
  22305. return animatable;
  22306. };
  22307. /**
  22308. * Begin a new animation on a given node
  22309. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22310. * @param {BABYLON.Animation[]} defines the list of animations to start
  22311. * @param {number} from defines the initial value
  22312. * @param {number} to defines the final value
  22313. * @param {boolean} loop defines if you want animation to loop (off by default)
  22314. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22315. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22316. * @returns the list of created animatables
  22317. */
  22318. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22319. if (speedRatio === undefined) {
  22320. speedRatio = 1.0;
  22321. }
  22322. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  22323. return animatable;
  22324. };
  22325. /**
  22326. * Begin a new animation on a given node and its hierarchy
  22327. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22328. * @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.
  22329. * @param {BABYLON.Animation[]} defines the list of animations to start
  22330. * @param {number} from defines the initial value
  22331. * @param {number} to defines the final value
  22332. * @param {boolean} loop defines if you want animation to loop (off by default)
  22333. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22334. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22335. * @returns the list of animatables created for all nodes
  22336. */
  22337. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22338. var children = target.getDescendants(directDescendantsOnly);
  22339. var result = [];
  22340. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  22341. var child = children_1[_i];
  22342. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  22343. }
  22344. return result;
  22345. };
  22346. Scene.prototype.getAnimatableByTarget = function (target) {
  22347. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22348. if (this._activeAnimatables[index].target === target) {
  22349. return this._activeAnimatables[index];
  22350. }
  22351. }
  22352. return null;
  22353. };
  22354. Object.defineProperty(Scene.prototype, "animatables", {
  22355. get: function () {
  22356. return this._activeAnimatables;
  22357. },
  22358. enumerable: true,
  22359. configurable: true
  22360. });
  22361. /**
  22362. * Will stop the animation of the given target
  22363. * @param target - the target
  22364. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  22365. * @see beginAnimation
  22366. */
  22367. Scene.prototype.stopAnimation = function (target, animationName) {
  22368. var animatable = this.getAnimatableByTarget(target);
  22369. if (animatable) {
  22370. animatable.stop(animationName);
  22371. }
  22372. };
  22373. /**
  22374. * Stops and removes all animations that have been applied to the scene
  22375. */
  22376. Scene.prototype.stopAllAnimations = function () {
  22377. if (this._activeAnimatables) {
  22378. for (var i = 0; i < this._activeAnimatables.length; i++) {
  22379. this._activeAnimatables[i].stop();
  22380. }
  22381. this._activeAnimatables = [];
  22382. }
  22383. };
  22384. Scene.prototype._animate = function () {
  22385. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  22386. return;
  22387. }
  22388. // Getting time
  22389. var now = BABYLON.Tools.Now;
  22390. if (!this._animationTimeLast) {
  22391. if (this._pendingData.length > 0) {
  22392. return;
  22393. }
  22394. this._animationTimeLast = now;
  22395. }
  22396. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  22397. this._animationTime += deltaTime;
  22398. this._animationTimeLast = now;
  22399. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22400. this._activeAnimatables[index]._animate(this._animationTime);
  22401. }
  22402. };
  22403. // Matrix
  22404. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  22405. this._useAlternateCameraConfiguration = active;
  22406. };
  22407. Scene.prototype.getViewMatrix = function () {
  22408. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  22409. };
  22410. Scene.prototype.getProjectionMatrix = function () {
  22411. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  22412. };
  22413. Scene.prototype.getTransformMatrix = function () {
  22414. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  22415. };
  22416. Scene.prototype.setTransformMatrix = function (view, projection) {
  22417. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  22418. return;
  22419. }
  22420. this._viewUpdateFlag = view.updateFlag;
  22421. this._projectionUpdateFlag = projection.updateFlag;
  22422. this._viewMatrix = view;
  22423. this._projectionMatrix = projection;
  22424. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22425. // Update frustum
  22426. if (!this._frustumPlanes) {
  22427. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22428. }
  22429. else {
  22430. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22431. }
  22432. if (this.activeCamera && this.activeCamera._alternateCamera) {
  22433. var otherCamera = this.activeCamera._alternateCamera;
  22434. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  22435. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  22436. }
  22437. if (this._sceneUbo.useUbo) {
  22438. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  22439. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  22440. this._sceneUbo.update();
  22441. }
  22442. };
  22443. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  22444. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  22445. return;
  22446. }
  22447. this._alternateViewUpdateFlag = view.updateFlag;
  22448. this._alternateProjectionUpdateFlag = projection.updateFlag;
  22449. this._alternateViewMatrix = view;
  22450. this._alternateProjectionMatrix = projection;
  22451. if (!this._alternateTransformMatrix) {
  22452. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  22453. }
  22454. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  22455. if (!this._alternateSceneUbo) {
  22456. this._createAlternateUbo();
  22457. }
  22458. if (this._alternateSceneUbo.useUbo) {
  22459. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  22460. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  22461. this._alternateSceneUbo.update();
  22462. }
  22463. };
  22464. Scene.prototype.getSceneUniformBuffer = function () {
  22465. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  22466. };
  22467. // Methods
  22468. Scene.prototype.getUniqueId = function () {
  22469. var result = Scene._uniqueIdCounter;
  22470. Scene._uniqueIdCounter++;
  22471. return result;
  22472. };
  22473. Scene.prototype.addMesh = function (newMesh) {
  22474. this.meshes.push(newMesh);
  22475. //notify the collision coordinator
  22476. if (this.collisionCoordinator) {
  22477. this.collisionCoordinator.onMeshAdded(newMesh);
  22478. }
  22479. newMesh._resyncLightSources();
  22480. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  22481. };
  22482. Scene.prototype.removeMesh = function (toRemove) {
  22483. var index = this.meshes.indexOf(toRemove);
  22484. if (index !== -1) {
  22485. // Remove from the scene if mesh found
  22486. this.meshes.splice(index, 1);
  22487. }
  22488. this.onMeshRemovedObservable.notifyObservers(toRemove);
  22489. return index;
  22490. };
  22491. Scene.prototype.addTransformNode = function (newTransformNode) {
  22492. this.transformNodes.push(newTransformNode);
  22493. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  22494. };
  22495. Scene.prototype.removeTransformNode = function (toRemove) {
  22496. var index = this.transformNodes.indexOf(toRemove);
  22497. if (index !== -1) {
  22498. // Remove from the scene if found
  22499. this.transformNodes.splice(index, 1);
  22500. }
  22501. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  22502. return index;
  22503. };
  22504. Scene.prototype.removeSkeleton = function (toRemove) {
  22505. var index = this.skeletons.indexOf(toRemove);
  22506. if (index !== -1) {
  22507. // Remove from the scene if found
  22508. this.skeletons.splice(index, 1);
  22509. }
  22510. return index;
  22511. };
  22512. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  22513. var index = this.morphTargetManagers.indexOf(toRemove);
  22514. if (index !== -1) {
  22515. // Remove from the scene if found
  22516. this.morphTargetManagers.splice(index, 1);
  22517. }
  22518. return index;
  22519. };
  22520. Scene.prototype.removeLight = function (toRemove) {
  22521. var index = this.lights.indexOf(toRemove);
  22522. if (index !== -1) {
  22523. // Remove from meshes
  22524. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22525. var mesh = _a[_i];
  22526. mesh._removeLightSource(toRemove);
  22527. }
  22528. // Remove from the scene if mesh found
  22529. this.lights.splice(index, 1);
  22530. this.sortLightsByPriority();
  22531. }
  22532. this.onLightRemovedObservable.notifyObservers(toRemove);
  22533. return index;
  22534. };
  22535. Scene.prototype.removeCamera = function (toRemove) {
  22536. var index = this.cameras.indexOf(toRemove);
  22537. if (index !== -1) {
  22538. // Remove from the scene if mesh found
  22539. this.cameras.splice(index, 1);
  22540. }
  22541. // Remove from activeCameras
  22542. var index2 = this.activeCameras.indexOf(toRemove);
  22543. if (index2 !== -1) {
  22544. // Remove from the scene if mesh found
  22545. this.activeCameras.splice(index2, 1);
  22546. }
  22547. // Reset the activeCamera
  22548. if (this.activeCamera === toRemove) {
  22549. if (this.cameras.length > 0) {
  22550. this.activeCamera = this.cameras[0];
  22551. }
  22552. else {
  22553. this.activeCamera = null;
  22554. }
  22555. }
  22556. this.onCameraRemovedObservable.notifyObservers(toRemove);
  22557. return index;
  22558. };
  22559. Scene.prototype.removeParticleSystem = function (toRemove) {
  22560. var index = this.particleSystems.indexOf(toRemove);
  22561. if (index !== -1) {
  22562. this.particleSystems.splice(index, 1);
  22563. }
  22564. return index;
  22565. };
  22566. ;
  22567. Scene.prototype.removeAnimation = function (toRemove) {
  22568. var index = this.animations.indexOf(toRemove);
  22569. if (index !== -1) {
  22570. this.animations.splice(index, 1);
  22571. }
  22572. return index;
  22573. };
  22574. ;
  22575. Scene.prototype.removeMultiMaterial = function (toRemove) {
  22576. var index = this.multiMaterials.indexOf(toRemove);
  22577. if (index !== -1) {
  22578. this.multiMaterials.splice(index, 1);
  22579. }
  22580. return index;
  22581. };
  22582. ;
  22583. Scene.prototype.removeMaterial = function (toRemove) {
  22584. var index = this.materials.indexOf(toRemove);
  22585. if (index !== -1) {
  22586. this.materials.splice(index, 1);
  22587. }
  22588. return index;
  22589. };
  22590. ;
  22591. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  22592. var index = this.lensFlareSystems.indexOf(toRemove);
  22593. if (index !== -1) {
  22594. this.lensFlareSystems.splice(index, 1);
  22595. }
  22596. return index;
  22597. };
  22598. ;
  22599. Scene.prototype.removeActionManager = function (toRemove) {
  22600. var index = this._actionManagers.indexOf(toRemove);
  22601. if (index !== -1) {
  22602. this._actionManagers.splice(index, 1);
  22603. }
  22604. return index;
  22605. };
  22606. ;
  22607. Scene.prototype.addLight = function (newLight) {
  22608. this.lights.push(newLight);
  22609. this.sortLightsByPriority();
  22610. // Add light to all meshes (To support if the light is removed and then readded)
  22611. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22612. var mesh = _a[_i];
  22613. if (mesh._lightSources.indexOf(newLight) === -1) {
  22614. mesh._lightSources.push(newLight);
  22615. mesh._resyncLightSources();
  22616. }
  22617. }
  22618. this.onNewLightAddedObservable.notifyObservers(newLight);
  22619. };
  22620. Scene.prototype.sortLightsByPriority = function () {
  22621. if (this.requireLightSorting) {
  22622. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  22623. }
  22624. };
  22625. Scene.prototype.addCamera = function (newCamera) {
  22626. this.cameras.push(newCamera);
  22627. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  22628. };
  22629. Scene.prototype.addSkeleton = function (newSkeleton) {
  22630. this.skeletons.push(newSkeleton);
  22631. };
  22632. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  22633. this.particleSystems.push(newParticleSystem);
  22634. };
  22635. Scene.prototype.addAnimation = function (newAnimation) {
  22636. this.animations.push(newAnimation);
  22637. };
  22638. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  22639. this.multiMaterials.push(newMultiMaterial);
  22640. };
  22641. Scene.prototype.addMaterial = function (newMaterial) {
  22642. this.materials.push(newMaterial);
  22643. };
  22644. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  22645. this.morphTargetManagers.push(newMorphTargetManager);
  22646. };
  22647. Scene.prototype.addGeometry = function (newGeometrie) {
  22648. this._geometries.push(newGeometrie);
  22649. };
  22650. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  22651. this.lensFlareSystems.push(newLensFlareSystem);
  22652. };
  22653. Scene.prototype.addActionManager = function (newActionManager) {
  22654. this._actionManagers.push(newActionManager);
  22655. };
  22656. /**
  22657. * Switch active camera
  22658. * @param {Camera} newCamera - new active camera
  22659. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  22660. */
  22661. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  22662. if (attachControl === void 0) { attachControl = true; }
  22663. var canvas = this._engine.getRenderingCanvas();
  22664. if (!canvas) {
  22665. return;
  22666. }
  22667. if (this.activeCamera) {
  22668. this.activeCamera.detachControl(canvas);
  22669. }
  22670. this.activeCamera = newCamera;
  22671. if (attachControl) {
  22672. newCamera.attachControl(canvas);
  22673. }
  22674. };
  22675. /**
  22676. * sets the active camera of the scene using its ID
  22677. * @param {string} id - the camera's ID
  22678. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22679. * @see activeCamera
  22680. */
  22681. Scene.prototype.setActiveCameraByID = function (id) {
  22682. var camera = this.getCameraByID(id);
  22683. if (camera) {
  22684. this.activeCamera = camera;
  22685. return camera;
  22686. }
  22687. return null;
  22688. };
  22689. /**
  22690. * sets the active camera of the scene using its name
  22691. * @param {string} name - the camera's name
  22692. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22693. * @see activeCamera
  22694. */
  22695. Scene.prototype.setActiveCameraByName = function (name) {
  22696. var camera = this.getCameraByName(name);
  22697. if (camera) {
  22698. this.activeCamera = camera;
  22699. return camera;
  22700. }
  22701. return null;
  22702. };
  22703. /**
  22704. * get an animation group using its name
  22705. * @param {string} the material's name
  22706. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  22707. */
  22708. Scene.prototype.getAnimationGroupByName = function (name) {
  22709. for (var index = 0; index < this.animationGroups.length; index++) {
  22710. if (this.animationGroups[index].name === name) {
  22711. return this.animationGroups[index];
  22712. }
  22713. }
  22714. return null;
  22715. };
  22716. /**
  22717. * get a material using its id
  22718. * @param {string} the material's ID
  22719. * @return {BABYLON.Material|null} the material or null if none found.
  22720. */
  22721. Scene.prototype.getMaterialByID = function (id) {
  22722. for (var index = 0; index < this.materials.length; index++) {
  22723. if (this.materials[index].id === id) {
  22724. return this.materials[index];
  22725. }
  22726. }
  22727. return null;
  22728. };
  22729. /**
  22730. * get a material using its name
  22731. * @param {string} the material's name
  22732. * @return {BABYLON.Material|null} the material or null if none found.
  22733. */
  22734. Scene.prototype.getMaterialByName = function (name) {
  22735. for (var index = 0; index < this.materials.length; index++) {
  22736. if (this.materials[index].name === name) {
  22737. return this.materials[index];
  22738. }
  22739. }
  22740. return null;
  22741. };
  22742. Scene.prototype.getLensFlareSystemByName = function (name) {
  22743. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22744. if (this.lensFlareSystems[index].name === name) {
  22745. return this.lensFlareSystems[index];
  22746. }
  22747. }
  22748. return null;
  22749. };
  22750. Scene.prototype.getLensFlareSystemByID = function (id) {
  22751. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22752. if (this.lensFlareSystems[index].id === id) {
  22753. return this.lensFlareSystems[index];
  22754. }
  22755. }
  22756. return null;
  22757. };
  22758. Scene.prototype.getCameraByID = function (id) {
  22759. for (var index = 0; index < this.cameras.length; index++) {
  22760. if (this.cameras[index].id === id) {
  22761. return this.cameras[index];
  22762. }
  22763. }
  22764. return null;
  22765. };
  22766. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  22767. for (var index = 0; index < this.cameras.length; index++) {
  22768. if (this.cameras[index].uniqueId === uniqueId) {
  22769. return this.cameras[index];
  22770. }
  22771. }
  22772. return null;
  22773. };
  22774. /**
  22775. * get a camera using its name
  22776. * @param {string} the camera's name
  22777. * @return {BABYLON.Camera|null} the camera or null if none found.
  22778. */
  22779. Scene.prototype.getCameraByName = function (name) {
  22780. for (var index = 0; index < this.cameras.length; index++) {
  22781. if (this.cameras[index].name === name) {
  22782. return this.cameras[index];
  22783. }
  22784. }
  22785. return null;
  22786. };
  22787. /**
  22788. * get a bone using its id
  22789. * @param {string} the bone's id
  22790. * @return {BABYLON.Bone|null} the bone or null if not found
  22791. */
  22792. Scene.prototype.getBoneByID = function (id) {
  22793. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22794. var skeleton = this.skeletons[skeletonIndex];
  22795. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22796. if (skeleton.bones[boneIndex].id === id) {
  22797. return skeleton.bones[boneIndex];
  22798. }
  22799. }
  22800. }
  22801. return null;
  22802. };
  22803. /**
  22804. * get a bone using its id
  22805. * @param {string} the bone's name
  22806. * @return {BABYLON.Bone|null} the bone or null if not found
  22807. */
  22808. Scene.prototype.getBoneByName = function (name) {
  22809. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22810. var skeleton = this.skeletons[skeletonIndex];
  22811. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22812. if (skeleton.bones[boneIndex].name === name) {
  22813. return skeleton.bones[boneIndex];
  22814. }
  22815. }
  22816. }
  22817. return null;
  22818. };
  22819. /**
  22820. * get a light node using its name
  22821. * @param {string} the light's name
  22822. * @return {BABYLON.Light|null} the light or null if none found.
  22823. */
  22824. Scene.prototype.getLightByName = function (name) {
  22825. for (var index = 0; index < this.lights.length; index++) {
  22826. if (this.lights[index].name === name) {
  22827. return this.lights[index];
  22828. }
  22829. }
  22830. return null;
  22831. };
  22832. /**
  22833. * get a light node using its ID
  22834. * @param {string} the light's id
  22835. * @return {BABYLON.Light|null} the light or null if none found.
  22836. */
  22837. Scene.prototype.getLightByID = function (id) {
  22838. for (var index = 0; index < this.lights.length; index++) {
  22839. if (this.lights[index].id === id) {
  22840. return this.lights[index];
  22841. }
  22842. }
  22843. return null;
  22844. };
  22845. /**
  22846. * get a light node using its scene-generated unique ID
  22847. * @param {number} the light's unique id
  22848. * @return {BABYLON.Light|null} the light or null if none found.
  22849. */
  22850. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  22851. for (var index = 0; index < this.lights.length; index++) {
  22852. if (this.lights[index].uniqueId === uniqueId) {
  22853. return this.lights[index];
  22854. }
  22855. }
  22856. return null;
  22857. };
  22858. /**
  22859. * get a particle system by id
  22860. * @param id {number} the particle system id
  22861. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  22862. */
  22863. Scene.prototype.getParticleSystemByID = function (id) {
  22864. for (var index = 0; index < this.particleSystems.length; index++) {
  22865. if (this.particleSystems[index].id === id) {
  22866. return this.particleSystems[index];
  22867. }
  22868. }
  22869. return null;
  22870. };
  22871. /**
  22872. * get a geometry using its ID
  22873. * @param {string} the geometry's id
  22874. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  22875. */
  22876. Scene.prototype.getGeometryByID = function (id) {
  22877. for (var index = 0; index < this._geometries.length; index++) {
  22878. if (this._geometries[index].id === id) {
  22879. return this._geometries[index];
  22880. }
  22881. }
  22882. return null;
  22883. };
  22884. /**
  22885. * add a new geometry to this scene.
  22886. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  22887. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  22888. * @return {boolean} was the geometry added or not
  22889. */
  22890. Scene.prototype.pushGeometry = function (geometry, force) {
  22891. if (!force && this.getGeometryByID(geometry.id)) {
  22892. return false;
  22893. }
  22894. this._geometries.push(geometry);
  22895. //notify the collision coordinator
  22896. if (this.collisionCoordinator) {
  22897. this.collisionCoordinator.onGeometryAdded(geometry);
  22898. }
  22899. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  22900. return true;
  22901. };
  22902. /**
  22903. * Removes an existing geometry
  22904. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  22905. * @return {boolean} was the geometry removed or not
  22906. */
  22907. Scene.prototype.removeGeometry = function (geometry) {
  22908. var index = this._geometries.indexOf(geometry);
  22909. if (index > -1) {
  22910. this._geometries.splice(index, 1);
  22911. //notify the collision coordinator
  22912. if (this.collisionCoordinator) {
  22913. this.collisionCoordinator.onGeometryDeleted(geometry);
  22914. }
  22915. this.onGeometryRemovedObservable.notifyObservers(geometry);
  22916. return true;
  22917. }
  22918. return false;
  22919. };
  22920. Scene.prototype.getGeometries = function () {
  22921. return this._geometries;
  22922. };
  22923. /**
  22924. * Get the first added mesh found of a given ID
  22925. * @param {string} id - the id to search for
  22926. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22927. */
  22928. Scene.prototype.getMeshByID = function (id) {
  22929. for (var index = 0; index < this.meshes.length; index++) {
  22930. if (this.meshes[index].id === id) {
  22931. return this.meshes[index];
  22932. }
  22933. }
  22934. return null;
  22935. };
  22936. Scene.prototype.getMeshesByID = function (id) {
  22937. return this.meshes.filter(function (m) {
  22938. return m.id === id;
  22939. });
  22940. };
  22941. /**
  22942. * Get the first added transform node found of a given ID
  22943. * @param {string} id - the id to search for
  22944. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  22945. */
  22946. Scene.prototype.getTransformNodeByID = function (id) {
  22947. for (var index = 0; index < this.transformNodes.length; index++) {
  22948. if (this.transformNodes[index].id === id) {
  22949. return this.transformNodes[index];
  22950. }
  22951. }
  22952. return null;
  22953. };
  22954. Scene.prototype.getTransformNodesByID = function (id) {
  22955. return this.transformNodes.filter(function (m) {
  22956. return m.id === id;
  22957. });
  22958. };
  22959. /**
  22960. * Get a mesh with its auto-generated unique id
  22961. * @param {number} uniqueId - the unique id to search for
  22962. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22963. */
  22964. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  22965. for (var index = 0; index < this.meshes.length; index++) {
  22966. if (this.meshes[index].uniqueId === uniqueId) {
  22967. return this.meshes[index];
  22968. }
  22969. }
  22970. return null;
  22971. };
  22972. /**
  22973. * Get a the last added mesh found of a given ID
  22974. * @param {string} id - the id to search for
  22975. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22976. */
  22977. Scene.prototype.getLastMeshByID = function (id) {
  22978. for (var index = this.meshes.length - 1; index >= 0; index--) {
  22979. if (this.meshes[index].id === id) {
  22980. return this.meshes[index];
  22981. }
  22982. }
  22983. return null;
  22984. };
  22985. /**
  22986. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  22987. * @param {string} id - the id to search for
  22988. * @return {BABYLON.Node|null} the node found or null if not found at all.
  22989. */
  22990. Scene.prototype.getLastEntryByID = function (id) {
  22991. var index;
  22992. for (index = this.meshes.length - 1; index >= 0; index--) {
  22993. if (this.meshes[index].id === id) {
  22994. return this.meshes[index];
  22995. }
  22996. }
  22997. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  22998. if (this.transformNodes[index].id === id) {
  22999. return this.transformNodes[index];
  23000. }
  23001. }
  23002. for (index = this.cameras.length - 1; index >= 0; index--) {
  23003. if (this.cameras[index].id === id) {
  23004. return this.cameras[index];
  23005. }
  23006. }
  23007. for (index = this.lights.length - 1; index >= 0; index--) {
  23008. if (this.lights[index].id === id) {
  23009. return this.lights[index];
  23010. }
  23011. }
  23012. return null;
  23013. };
  23014. Scene.prototype.getNodeByID = function (id) {
  23015. var mesh = this.getMeshByID(id);
  23016. if (mesh) {
  23017. return mesh;
  23018. }
  23019. var light = this.getLightByID(id);
  23020. if (light) {
  23021. return light;
  23022. }
  23023. var camera = this.getCameraByID(id);
  23024. if (camera) {
  23025. return camera;
  23026. }
  23027. var bone = this.getBoneByID(id);
  23028. return bone;
  23029. };
  23030. Scene.prototype.getNodeByName = function (name) {
  23031. var mesh = this.getMeshByName(name);
  23032. if (mesh) {
  23033. return mesh;
  23034. }
  23035. var light = this.getLightByName(name);
  23036. if (light) {
  23037. return light;
  23038. }
  23039. var camera = this.getCameraByName(name);
  23040. if (camera) {
  23041. return camera;
  23042. }
  23043. var bone = this.getBoneByName(name);
  23044. return bone;
  23045. };
  23046. Scene.prototype.getMeshByName = function (name) {
  23047. for (var index = 0; index < this.meshes.length; index++) {
  23048. if (this.meshes[index].name === name) {
  23049. return this.meshes[index];
  23050. }
  23051. }
  23052. return null;
  23053. };
  23054. Scene.prototype.getTransformNodeByName = function (name) {
  23055. for (var index = 0; index < this.transformNodes.length; index++) {
  23056. if (this.transformNodes[index].name === name) {
  23057. return this.transformNodes[index];
  23058. }
  23059. }
  23060. return null;
  23061. };
  23062. Scene.prototype.getSoundByName = function (name) {
  23063. var index;
  23064. if (BABYLON.AudioEngine) {
  23065. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23066. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23067. return this.mainSoundTrack.soundCollection[index];
  23068. }
  23069. }
  23070. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23071. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23072. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23073. return this.soundTracks[sdIndex].soundCollection[index];
  23074. }
  23075. }
  23076. }
  23077. }
  23078. return null;
  23079. };
  23080. Scene.prototype.getLastSkeletonByID = function (id) {
  23081. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23082. if (this.skeletons[index].id === id) {
  23083. return this.skeletons[index];
  23084. }
  23085. }
  23086. return null;
  23087. };
  23088. Scene.prototype.getSkeletonById = function (id) {
  23089. for (var index = 0; index < this.skeletons.length; index++) {
  23090. if (this.skeletons[index].id === id) {
  23091. return this.skeletons[index];
  23092. }
  23093. }
  23094. return null;
  23095. };
  23096. Scene.prototype.getSkeletonByName = function (name) {
  23097. for (var index = 0; index < this.skeletons.length; index++) {
  23098. if (this.skeletons[index].name === name) {
  23099. return this.skeletons[index];
  23100. }
  23101. }
  23102. return null;
  23103. };
  23104. Scene.prototype.getMorphTargetManagerById = function (id) {
  23105. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23106. if (this.morphTargetManagers[index].uniqueId === id) {
  23107. return this.morphTargetManagers[index];
  23108. }
  23109. }
  23110. return null;
  23111. };
  23112. Scene.prototype.isActiveMesh = function (mesh) {
  23113. return (this._activeMeshes.indexOf(mesh) !== -1);
  23114. };
  23115. /**
  23116. * Return a the first highlight layer of the scene with a given name.
  23117. * @param name The name of the highlight layer to look for.
  23118. * @return The highlight layer if found otherwise null.
  23119. */
  23120. Scene.prototype.getHighlightLayerByName = function (name) {
  23121. for (var index = 0; index < this.highlightLayers.length; index++) {
  23122. if (this.highlightLayers[index].name === name) {
  23123. return this.highlightLayers[index];
  23124. }
  23125. }
  23126. return null;
  23127. };
  23128. Object.defineProperty(Scene.prototype, "uid", {
  23129. /**
  23130. * Return a unique id as a string which can serve as an identifier for the scene
  23131. */
  23132. get: function () {
  23133. if (!this._uid) {
  23134. this._uid = BABYLON.Tools.RandomId();
  23135. }
  23136. return this._uid;
  23137. },
  23138. enumerable: true,
  23139. configurable: true
  23140. });
  23141. /**
  23142. * Add an externaly attached data from its key.
  23143. * This method call will fail and return false, if such key already exists.
  23144. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23145. * @param key the unique key that identifies the data
  23146. * @param data the data object to associate to the key for this Engine instance
  23147. * @return true if no such key were already present and the data was added successfully, false otherwise
  23148. */
  23149. Scene.prototype.addExternalData = function (key, data) {
  23150. if (!this._externalData) {
  23151. this._externalData = new BABYLON.StringDictionary();
  23152. }
  23153. return this._externalData.add(key, data);
  23154. };
  23155. /**
  23156. * Get an externaly attached data from its key
  23157. * @param key the unique key that identifies the data
  23158. * @return the associated data, if present (can be null), or undefined if not present
  23159. */
  23160. Scene.prototype.getExternalData = function (key) {
  23161. if (!this._externalData) {
  23162. return null;
  23163. }
  23164. return this._externalData.get(key);
  23165. };
  23166. /**
  23167. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23168. * @param key the unique key that identifies the data
  23169. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23170. * @return the associated data, can be null if the factory returned null.
  23171. */
  23172. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23173. if (!this._externalData) {
  23174. this._externalData = new BABYLON.StringDictionary();
  23175. }
  23176. return this._externalData.getOrAddWithFactory(key, factory);
  23177. };
  23178. /**
  23179. * Remove an externaly attached data from the Engine instance
  23180. * @param key the unique key that identifies the data
  23181. * @return true if the data was successfully removed, false if it doesn't exist
  23182. */
  23183. Scene.prototype.removeExternalData = function (key) {
  23184. return this._externalData.remove(key);
  23185. };
  23186. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23187. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23188. if (mesh.showSubMeshesBoundingBox) {
  23189. var boundingInfo = subMesh.getBoundingInfo();
  23190. if (boundingInfo !== null && boundingInfo !== undefined) {
  23191. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23192. }
  23193. }
  23194. var material = subMesh.getMaterial();
  23195. if (material !== null && material !== undefined) {
  23196. // Render targets
  23197. if (material.getRenderTargetTextures !== undefined) {
  23198. if (this._processedMaterials.indexOf(material) === -1) {
  23199. this._processedMaterials.push(material);
  23200. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23201. }
  23202. }
  23203. // Dispatch
  23204. this._activeIndices.addCount(subMesh.indexCount, false);
  23205. this._renderingManager.dispatch(subMesh, mesh, material);
  23206. }
  23207. }
  23208. };
  23209. Scene.prototype._isInIntermediateRendering = function () {
  23210. return this._intermediateRendering;
  23211. };
  23212. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23213. this._activeMeshCandidateProvider = provider;
  23214. };
  23215. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23216. return this._activeMeshCandidateProvider;
  23217. };
  23218. /**
  23219. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  23220. */
  23221. Scene.prototype.freezeActiveMeshes = function () {
  23222. this._evaluateActiveMeshes();
  23223. this._activeMeshesFrozen = true;
  23224. return this;
  23225. };
  23226. /**
  23227. * Use this function to restart evaluating active meshes on every frame
  23228. */
  23229. Scene.prototype.unfreezeActiveMeshes = function () {
  23230. this._activeMeshesFrozen = false;
  23231. return this;
  23232. };
  23233. Scene.prototype._evaluateActiveMeshes = function () {
  23234. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  23235. return;
  23236. }
  23237. if (!this.activeCamera) {
  23238. return;
  23239. }
  23240. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  23241. this.activeCamera._activeMeshes.reset();
  23242. this._activeMeshes.reset();
  23243. this._renderingManager.reset();
  23244. this._processedMaterials.reset();
  23245. this._activeParticleSystems.reset();
  23246. this._activeSkeletons.reset();
  23247. this._softwareSkinnedMeshes.reset();
  23248. if (this._boundingBoxRenderer) {
  23249. this._boundingBoxRenderer.reset();
  23250. }
  23251. // Meshes
  23252. var meshes;
  23253. var len;
  23254. var checkIsEnabled = true;
  23255. // Determine mesh candidates
  23256. if (this._activeMeshCandidateProvider !== undefined) {
  23257. // Use _activeMeshCandidateProvider
  23258. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  23259. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  23260. if (meshes !== undefined) {
  23261. len = meshes.length;
  23262. }
  23263. else {
  23264. len = 0;
  23265. }
  23266. }
  23267. else if (this._selectionOctree !== undefined) {
  23268. // Octree
  23269. var selection = this._selectionOctree.select(this._frustumPlanes);
  23270. meshes = selection.data;
  23271. len = selection.length;
  23272. }
  23273. else {
  23274. // Full scene traversal
  23275. len = this.meshes.length;
  23276. meshes = this.meshes;
  23277. }
  23278. // Check each mesh
  23279. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  23280. mesh = meshes[meshIndex];
  23281. if (mesh.isBlocked) {
  23282. continue;
  23283. }
  23284. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  23285. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  23286. continue;
  23287. }
  23288. mesh.computeWorldMatrix();
  23289. // Intersections
  23290. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  23291. this._meshesForIntersections.pushNoDuplicate(mesh);
  23292. }
  23293. // Switch to current LOD
  23294. meshLOD = mesh.getLOD(this.activeCamera);
  23295. if (meshLOD === undefined || meshLOD === null) {
  23296. continue;
  23297. }
  23298. mesh._preActivate();
  23299. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  23300. this._activeMeshes.push(mesh);
  23301. this.activeCamera._activeMeshes.push(mesh);
  23302. mesh._activate(this._renderId);
  23303. if (meshLOD !== mesh) {
  23304. meshLOD._activate(this._renderId);
  23305. }
  23306. this._activeMesh(mesh, meshLOD);
  23307. }
  23308. }
  23309. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  23310. // Particle systems
  23311. if (this.particlesEnabled) {
  23312. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  23313. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  23314. var particleSystem = this.particleSystems[particleIndex];
  23315. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  23316. continue;
  23317. }
  23318. var emitter = particleSystem.emitter;
  23319. if (!emitter.position || emitter.isEnabled()) {
  23320. this._activeParticleSystems.push(particleSystem);
  23321. particleSystem.animate();
  23322. this._renderingManager.dispatchParticles(particleSystem);
  23323. }
  23324. }
  23325. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  23326. }
  23327. };
  23328. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  23329. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  23330. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  23331. mesh.skeleton.prepare();
  23332. }
  23333. if (!mesh.computeBonesUsingShaders) {
  23334. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  23335. }
  23336. }
  23337. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  23338. var boundingInfo = sourceMesh.getBoundingInfo();
  23339. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23340. }
  23341. if (mesh !== undefined && mesh !== null
  23342. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  23343. // Submeshes Octrees
  23344. var len;
  23345. var subMeshes;
  23346. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  23347. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  23348. len = intersections.length;
  23349. subMeshes = intersections.data;
  23350. }
  23351. else {
  23352. subMeshes = mesh.subMeshes;
  23353. len = subMeshes.length;
  23354. }
  23355. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  23356. subMesh = subMeshes[subIndex];
  23357. this._evaluateSubMesh(subMesh, mesh);
  23358. }
  23359. }
  23360. };
  23361. Scene.prototype.updateTransformMatrix = function (force) {
  23362. if (!this.activeCamera) {
  23363. return;
  23364. }
  23365. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  23366. };
  23367. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  23368. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  23369. };
  23370. Scene.prototype._renderForCamera = function (camera) {
  23371. if (camera && camera._skipRendering) {
  23372. return;
  23373. }
  23374. var engine = this._engine;
  23375. this.activeCamera = camera;
  23376. if (!this.activeCamera)
  23377. throw new Error("Active camera not set");
  23378. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23379. // Viewport
  23380. engine.setViewport(this.activeCamera.viewport);
  23381. // Camera
  23382. this.resetCachedMaterial();
  23383. this._renderId++;
  23384. this.activeCamera.update();
  23385. this.updateTransformMatrix();
  23386. if (camera._alternateCamera) {
  23387. this.updateAlternateTransformMatrix(camera._alternateCamera);
  23388. this._alternateRendering = true;
  23389. }
  23390. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  23391. // Meshes
  23392. this._evaluateActiveMeshes();
  23393. // Software skinning
  23394. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  23395. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  23396. mesh.applySkeleton(mesh.skeleton);
  23397. }
  23398. // Render targets
  23399. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23400. var needsRestoreFrameBuffer = false;
  23401. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  23402. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  23403. }
  23404. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  23405. this._intermediateRendering = true;
  23406. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23407. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  23408. var renderTarget = this._renderTargets.data[renderIndex];
  23409. if (renderTarget._shouldRender()) {
  23410. this._renderId++;
  23411. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  23412. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  23413. }
  23414. }
  23415. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23416. this._intermediateRendering = false;
  23417. this._renderId++;
  23418. needsRestoreFrameBuffer = true; // Restore back buffer
  23419. }
  23420. // Render HighlightLayer Texture
  23421. var stencilState = this._engine.getStencilBuffer();
  23422. var renderhighlights = false;
  23423. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  23424. this._intermediateRendering = true;
  23425. for (var i = 0; i < this.highlightLayers.length; i++) {
  23426. var highlightLayer = this.highlightLayers[i];
  23427. if (highlightLayer.shouldRender() &&
  23428. (!highlightLayer.camera ||
  23429. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  23430. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  23431. renderhighlights = true;
  23432. var renderTarget = highlightLayer._mainTexture;
  23433. if (renderTarget._shouldRender()) {
  23434. this._renderId++;
  23435. renderTarget.render(false, false);
  23436. needsRestoreFrameBuffer = true;
  23437. }
  23438. }
  23439. }
  23440. this._intermediateRendering = false;
  23441. this._renderId++;
  23442. }
  23443. if (needsRestoreFrameBuffer) {
  23444. engine.restoreDefaultFramebuffer(); // Restore back buffer
  23445. }
  23446. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23447. // Prepare Frame
  23448. this.postProcessManager._prepareFrame();
  23449. // Backgrounds
  23450. var layerIndex;
  23451. var layer;
  23452. if (this.layers.length) {
  23453. engine.setDepthBuffer(false);
  23454. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23455. layer = this.layers[layerIndex];
  23456. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23457. layer.render();
  23458. }
  23459. }
  23460. engine.setDepthBuffer(true);
  23461. }
  23462. // Activate HighlightLayer stencil
  23463. if (renderhighlights) {
  23464. this._engine.setStencilBuffer(true);
  23465. }
  23466. // Render
  23467. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  23468. this._renderingManager.render(null, null, true, true);
  23469. this.onAfterDrawPhaseObservable.notifyObservers(this);
  23470. // Restore HighlightLayer stencil
  23471. if (renderhighlights) {
  23472. this._engine.setStencilBuffer(stencilState);
  23473. }
  23474. // Bounding boxes
  23475. if (this._boundingBoxRenderer) {
  23476. this._boundingBoxRenderer.render();
  23477. }
  23478. // Lens flares
  23479. if (this.lensFlaresEnabled) {
  23480. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23481. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  23482. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  23483. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  23484. lensFlareSystem.render();
  23485. }
  23486. }
  23487. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23488. }
  23489. // Foregrounds
  23490. if (this.layers.length) {
  23491. engine.setDepthBuffer(false);
  23492. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23493. layer = this.layers[layerIndex];
  23494. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23495. layer.render();
  23496. }
  23497. }
  23498. engine.setDepthBuffer(true);
  23499. }
  23500. // Highlight Layer
  23501. if (renderhighlights) {
  23502. engine.setDepthBuffer(false);
  23503. for (var i = 0; i < this.highlightLayers.length; i++) {
  23504. if (this.highlightLayers[i].shouldRender()) {
  23505. this.highlightLayers[i].render();
  23506. }
  23507. }
  23508. engine.setDepthBuffer(true);
  23509. }
  23510. // Finalize frame
  23511. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  23512. // Reset some special arrays
  23513. this._renderTargets.reset();
  23514. this._alternateRendering = false;
  23515. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  23516. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23517. };
  23518. Scene.prototype._processSubCameras = function (camera) {
  23519. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  23520. this._renderForCamera(camera);
  23521. return;
  23522. }
  23523. // Update camera
  23524. if (this.activeCamera) {
  23525. this.activeCamera.update();
  23526. }
  23527. // rig cameras
  23528. for (var index = 0; index < camera._rigCameras.length; index++) {
  23529. this._renderForCamera(camera._rigCameras[index]);
  23530. }
  23531. this.activeCamera = camera;
  23532. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  23533. };
  23534. Scene.prototype._checkIntersections = function () {
  23535. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  23536. var sourceMesh = this._meshesForIntersections.data[index];
  23537. if (!sourceMesh.actionManager) {
  23538. continue;
  23539. }
  23540. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  23541. var action = sourceMesh.actionManager.actions[actionIndex];
  23542. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23543. var parameters = action.getTriggerParameter();
  23544. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  23545. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  23546. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  23547. if (areIntersecting && currentIntersectionInProgress === -1) {
  23548. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  23549. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23550. sourceMesh._intersectionsInProgress.push(otherMesh);
  23551. }
  23552. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23553. sourceMesh._intersectionsInProgress.push(otherMesh);
  23554. }
  23555. }
  23556. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  23557. //They intersected, and now they don't.
  23558. //is this trigger an exit trigger? execute an event.
  23559. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23560. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23561. }
  23562. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  23563. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23564. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  23565. }
  23566. }
  23567. }
  23568. }
  23569. }
  23570. };
  23571. Scene.prototype.render = function () {
  23572. if (this.isDisposed) {
  23573. return;
  23574. }
  23575. this._activeParticles.fetchNewFrame();
  23576. this._totalVertices.fetchNewFrame();
  23577. this._activeIndices.fetchNewFrame();
  23578. this._activeBones.fetchNewFrame();
  23579. this._meshesForIntersections.reset();
  23580. this.resetCachedMaterial();
  23581. this.onBeforeAnimationsObservable.notifyObservers(this);
  23582. // Actions
  23583. if (this.actionManager) {
  23584. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  23585. }
  23586. //Simplification Queue
  23587. if (this.simplificationQueue && !this.simplificationQueue.running) {
  23588. this.simplificationQueue.executeNext();
  23589. }
  23590. if (this._engine.isDeterministicLockStep()) {
  23591. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  23592. var defaultFPS = (60.0 / 1000.0);
  23593. var defaultFrameTime = 1000 / 60; // frame time in MS
  23594. if (this._physicsEngine) {
  23595. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  23596. }
  23597. var stepsTaken = 0;
  23598. var maxSubSteps = this._engine.getLockstepMaxSteps();
  23599. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  23600. internalSteps = Math.min(internalSteps, maxSubSteps);
  23601. do {
  23602. this.onBeforeStepObservable.notifyObservers(this);
  23603. // Animations
  23604. this._animationRatio = defaultFrameTime * defaultFPS;
  23605. this._animate();
  23606. this.onAfterAnimationsObservable.notifyObservers(this);
  23607. // Physics
  23608. if (this._physicsEngine) {
  23609. this.onBeforePhysicsObservable.notifyObservers(this);
  23610. this._physicsEngine._step(defaultFrameTime / 1000);
  23611. this.onAfterPhysicsObservable.notifyObservers(this);
  23612. }
  23613. this.onAfterStepObservable.notifyObservers(this);
  23614. this._currentStepId++;
  23615. stepsTaken++;
  23616. deltaTime -= defaultFrameTime;
  23617. } while (deltaTime > 0 && stepsTaken < internalSteps);
  23618. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  23619. }
  23620. else {
  23621. // Animations
  23622. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  23623. this._animationRatio = deltaTime * (60.0 / 1000.0);
  23624. this._animate();
  23625. this.onAfterAnimationsObservable.notifyObservers(this);
  23626. // Physics
  23627. if (this._physicsEngine) {
  23628. this.onBeforePhysicsObservable.notifyObservers(this);
  23629. this._physicsEngine._step(deltaTime / 1000.0);
  23630. this.onAfterPhysicsObservable.notifyObservers(this);
  23631. }
  23632. }
  23633. // update gamepad manager
  23634. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  23635. this._gamepadManager._checkGamepadsStatus();
  23636. }
  23637. // Before render
  23638. this.onBeforeRenderObservable.notifyObservers(this);
  23639. // Customs render targets
  23640. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23641. var engine = this.getEngine();
  23642. var currentActiveCamera = this.activeCamera;
  23643. if (this.renderTargetsEnabled) {
  23644. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23645. this._intermediateRendering = true;
  23646. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  23647. var renderTarget = this.customRenderTargets[customIndex];
  23648. if (renderTarget._shouldRender()) {
  23649. this._renderId++;
  23650. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  23651. if (!this.activeCamera)
  23652. throw new Error("Active camera not set");
  23653. // Viewport
  23654. engine.setViewport(this.activeCamera.viewport);
  23655. // Camera
  23656. this.updateTransformMatrix();
  23657. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  23658. }
  23659. }
  23660. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23661. this._intermediateRendering = false;
  23662. this._renderId++;
  23663. }
  23664. // Restore back buffer
  23665. if (this.customRenderTargets.length > 0) {
  23666. engine.restoreDefaultFramebuffer();
  23667. }
  23668. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23669. this.activeCamera = currentActiveCamera;
  23670. // Procedural textures
  23671. if (this.proceduralTexturesEnabled) {
  23672. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23673. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  23674. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  23675. if (proceduralTexture._shouldRender()) {
  23676. proceduralTexture.render();
  23677. }
  23678. }
  23679. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23680. }
  23681. // Clear
  23682. if (this.autoClearDepthAndStencil || this.autoClear) {
  23683. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  23684. }
  23685. // Shadows
  23686. if (this.shadowsEnabled) {
  23687. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  23688. var light = this.lights[lightIndex];
  23689. var shadowGenerator = light.getShadowGenerator();
  23690. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  23691. var shadowMap = (shadowGenerator.getShadowMap());
  23692. if (this.textures.indexOf(shadowMap) !== -1) {
  23693. this._renderTargets.push(shadowMap);
  23694. }
  23695. }
  23696. }
  23697. }
  23698. // Depth renderer
  23699. if (this._depthRenderer) {
  23700. this._renderTargets.push(this._depthRenderer.getDepthMap());
  23701. }
  23702. // Geometry renderer
  23703. if (this._geometryBufferRenderer) {
  23704. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  23705. }
  23706. // RenderPipeline
  23707. if (this._postProcessRenderPipelineManager) {
  23708. this._postProcessRenderPipelineManager.update();
  23709. }
  23710. // Multi-cameras?
  23711. if (this.activeCameras.length > 0) {
  23712. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  23713. if (cameraIndex > 0) {
  23714. this._engine.clear(null, false, true, true);
  23715. }
  23716. this._processSubCameras(this.activeCameras[cameraIndex]);
  23717. }
  23718. }
  23719. else {
  23720. if (!this.activeCamera) {
  23721. throw new Error("No camera defined");
  23722. }
  23723. this._processSubCameras(this.activeCamera);
  23724. }
  23725. // Intersection checks
  23726. this._checkIntersections();
  23727. // Update the audio listener attached to the camera
  23728. if (BABYLON.AudioEngine) {
  23729. this._updateAudioParameters();
  23730. }
  23731. // After render
  23732. if (this.afterRender) {
  23733. this.afterRender();
  23734. }
  23735. this.onAfterRenderObservable.notifyObservers(this);
  23736. // Cleaning
  23737. for (var index = 0; index < this._toBeDisposed.length; index++) {
  23738. var data = this._toBeDisposed.data[index];
  23739. if (data) {
  23740. data.dispose();
  23741. }
  23742. this._toBeDisposed[index] = null;
  23743. }
  23744. this._toBeDisposed.reset();
  23745. if (this.dumpNextRenderTargets) {
  23746. this.dumpNextRenderTargets = false;
  23747. }
  23748. this._activeBones.addCount(0, true);
  23749. this._activeIndices.addCount(0, true);
  23750. this._activeParticles.addCount(0, true);
  23751. };
  23752. Scene.prototype._updateAudioParameters = function () {
  23753. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  23754. return;
  23755. }
  23756. var listeningCamera;
  23757. var audioEngine = BABYLON.Engine.audioEngine;
  23758. if (this.activeCameras.length > 0) {
  23759. listeningCamera = this.activeCameras[0];
  23760. }
  23761. else {
  23762. listeningCamera = this.activeCamera;
  23763. }
  23764. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  23765. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  23766. // for VR cameras
  23767. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  23768. listeningCamera = listeningCamera.rigCameras[0];
  23769. }
  23770. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  23771. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  23772. cameraDirection.normalize();
  23773. // To avoid some errors on GearVR
  23774. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  23775. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  23776. }
  23777. var i;
  23778. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23779. var sound = this.mainSoundTrack.soundCollection[i];
  23780. if (sound.useCustomAttenuation) {
  23781. sound.updateDistanceFromListener();
  23782. }
  23783. }
  23784. for (i = 0; i < this.soundTracks.length; i++) {
  23785. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23786. sound = this.soundTracks[i].soundCollection[j];
  23787. if (sound.useCustomAttenuation) {
  23788. sound.updateDistanceFromListener();
  23789. }
  23790. }
  23791. }
  23792. }
  23793. };
  23794. Object.defineProperty(Scene.prototype, "audioEnabled", {
  23795. // Audio
  23796. get: function () {
  23797. return this._audioEnabled;
  23798. },
  23799. set: function (value) {
  23800. this._audioEnabled = value;
  23801. if (BABYLON.AudioEngine) {
  23802. if (this._audioEnabled) {
  23803. this._enableAudio();
  23804. }
  23805. else {
  23806. this._disableAudio();
  23807. }
  23808. }
  23809. },
  23810. enumerable: true,
  23811. configurable: true
  23812. });
  23813. Scene.prototype._disableAudio = function () {
  23814. var i;
  23815. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23816. this.mainSoundTrack.soundCollection[i].pause();
  23817. }
  23818. for (i = 0; i < this.soundTracks.length; i++) {
  23819. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23820. this.soundTracks[i].soundCollection[j].pause();
  23821. }
  23822. }
  23823. };
  23824. Scene.prototype._enableAudio = function () {
  23825. var i;
  23826. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23827. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  23828. this.mainSoundTrack.soundCollection[i].play();
  23829. }
  23830. }
  23831. for (i = 0; i < this.soundTracks.length; i++) {
  23832. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23833. if (this.soundTracks[i].soundCollection[j].isPaused) {
  23834. this.soundTracks[i].soundCollection[j].play();
  23835. }
  23836. }
  23837. }
  23838. };
  23839. Object.defineProperty(Scene.prototype, "headphone", {
  23840. get: function () {
  23841. return this._headphone;
  23842. },
  23843. set: function (value) {
  23844. this._headphone = value;
  23845. if (BABYLON.AudioEngine) {
  23846. if (this._headphone) {
  23847. this._switchAudioModeForHeadphones();
  23848. }
  23849. else {
  23850. this._switchAudioModeForNormalSpeakers();
  23851. }
  23852. }
  23853. },
  23854. enumerable: true,
  23855. configurable: true
  23856. });
  23857. Scene.prototype._switchAudioModeForHeadphones = function () {
  23858. this.mainSoundTrack.switchPanningModelToHRTF();
  23859. for (var i = 0; i < this.soundTracks.length; i++) {
  23860. this.soundTracks[i].switchPanningModelToHRTF();
  23861. }
  23862. };
  23863. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  23864. this.mainSoundTrack.switchPanningModelToEqualPower();
  23865. for (var i = 0; i < this.soundTracks.length; i++) {
  23866. this.soundTracks[i].switchPanningModelToEqualPower();
  23867. }
  23868. };
  23869. Scene.prototype.enableDepthRenderer = function () {
  23870. if (this._depthRenderer) {
  23871. return this._depthRenderer;
  23872. }
  23873. this._depthRenderer = new BABYLON.DepthRenderer(this);
  23874. return this._depthRenderer;
  23875. };
  23876. Scene.prototype.disableDepthRenderer = function () {
  23877. if (!this._depthRenderer) {
  23878. return;
  23879. }
  23880. this._depthRenderer.dispose();
  23881. this._depthRenderer = null;
  23882. };
  23883. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  23884. if (ratio === void 0) { ratio = 1; }
  23885. if (this._geometryBufferRenderer) {
  23886. return this._geometryBufferRenderer;
  23887. }
  23888. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  23889. if (!this._geometryBufferRenderer.isSupported) {
  23890. this._geometryBufferRenderer = null;
  23891. }
  23892. return this._geometryBufferRenderer;
  23893. };
  23894. Scene.prototype.disableGeometryBufferRenderer = function () {
  23895. if (!this._geometryBufferRenderer) {
  23896. return;
  23897. }
  23898. this._geometryBufferRenderer.dispose();
  23899. this._geometryBufferRenderer = null;
  23900. };
  23901. Scene.prototype.freezeMaterials = function () {
  23902. for (var i = 0; i < this.materials.length; i++) {
  23903. this.materials[i].freeze();
  23904. }
  23905. };
  23906. Scene.prototype.unfreezeMaterials = function () {
  23907. for (var i = 0; i < this.materials.length; i++) {
  23908. this.materials[i].unfreeze();
  23909. }
  23910. };
  23911. Scene.prototype.dispose = function () {
  23912. this.beforeRender = null;
  23913. this.afterRender = null;
  23914. this.skeletons = [];
  23915. this.morphTargetManagers = [];
  23916. this.importedMeshesFiles = new Array();
  23917. this.stopAllAnimations();
  23918. this.resetCachedMaterial();
  23919. if (this._depthRenderer) {
  23920. this._depthRenderer.dispose();
  23921. }
  23922. if (this._gamepadManager) {
  23923. this._gamepadManager.dispose();
  23924. this._gamepadManager = null;
  23925. }
  23926. // Smart arrays
  23927. if (this.activeCamera) {
  23928. this.activeCamera._activeMeshes.dispose();
  23929. this.activeCamera = null;
  23930. }
  23931. this._activeMeshes.dispose();
  23932. this._renderingManager.dispose();
  23933. this._processedMaterials.dispose();
  23934. this._activeParticleSystems.dispose();
  23935. this._activeSkeletons.dispose();
  23936. this._softwareSkinnedMeshes.dispose();
  23937. this._renderTargets.dispose();
  23938. if (this._boundingBoxRenderer) {
  23939. this._boundingBoxRenderer.dispose();
  23940. }
  23941. this._meshesForIntersections.dispose();
  23942. this._toBeDisposed.dispose();
  23943. // Abort active requests
  23944. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  23945. var request = _a[_i];
  23946. request.abort();
  23947. }
  23948. // Debug layer
  23949. if (this._debugLayer) {
  23950. this._debugLayer.hide();
  23951. }
  23952. // Events
  23953. this.onDisposeObservable.notifyObservers(this);
  23954. this.onDisposeObservable.clear();
  23955. this.onBeforeRenderObservable.clear();
  23956. this.onAfterRenderObservable.clear();
  23957. this.OnBeforeRenderTargetsRenderObservable.clear();
  23958. this.OnAfterRenderTargetsRenderObservable.clear();
  23959. this.onAfterStepObservable.clear();
  23960. this.onBeforeStepObservable.clear();
  23961. this.onBeforeActiveMeshesEvaluationObservable.clear();
  23962. this.onAfterActiveMeshesEvaluationObservable.clear();
  23963. this.onBeforeParticlesRenderingObservable.clear();
  23964. this.onAfterParticlesRenderingObservable.clear();
  23965. this.onBeforeSpritesRenderingObservable.clear();
  23966. this.onAfterSpritesRenderingObservable.clear();
  23967. this.onBeforeDrawPhaseObservable.clear();
  23968. this.onAfterDrawPhaseObservable.clear();
  23969. this.onBeforePhysicsObservable.clear();
  23970. this.onAfterPhysicsObservable.clear();
  23971. this.onBeforeAnimationsObservable.clear();
  23972. this.onAfterAnimationsObservable.clear();
  23973. this.onDataLoadedObservable.clear();
  23974. this.detachControl();
  23975. // Release sounds & sounds tracks
  23976. if (BABYLON.AudioEngine) {
  23977. this.disposeSounds();
  23978. }
  23979. // VR Helper
  23980. if (this.VRHelper) {
  23981. this.VRHelper.dispose();
  23982. }
  23983. // Detach cameras
  23984. var canvas = this._engine.getRenderingCanvas();
  23985. if (canvas) {
  23986. var index;
  23987. for (index = 0; index < this.cameras.length; index++) {
  23988. this.cameras[index].detachControl(canvas);
  23989. }
  23990. }
  23991. // Release animation groups
  23992. while (this.animationGroups.length) {
  23993. this.animationGroups[0].dispose();
  23994. }
  23995. // Release lights
  23996. while (this.lights.length) {
  23997. this.lights[0].dispose();
  23998. }
  23999. // Release meshes
  24000. while (this.meshes.length) {
  24001. this.meshes[0].dispose(true);
  24002. }
  24003. while (this.transformNodes.length) {
  24004. this.removeTransformNode(this.transformNodes[0]);
  24005. }
  24006. // Release cameras
  24007. while (this.cameras.length) {
  24008. this.cameras[0].dispose();
  24009. }
  24010. // Release materials
  24011. if (this.defaultMaterial) {
  24012. this.defaultMaterial.dispose();
  24013. }
  24014. while (this.multiMaterials.length) {
  24015. this.multiMaterials[0].dispose();
  24016. }
  24017. while (this.materials.length) {
  24018. this.materials[0].dispose();
  24019. }
  24020. // Release particles
  24021. while (this.particleSystems.length) {
  24022. this.particleSystems[0].dispose();
  24023. }
  24024. // Release sprites
  24025. while (this.spriteManagers.length) {
  24026. this.spriteManagers[0].dispose();
  24027. }
  24028. // Release postProcesses
  24029. while (this.postProcesses.length) {
  24030. this.postProcesses[0].dispose();
  24031. }
  24032. // Release layers
  24033. while (this.layers.length) {
  24034. this.layers[0].dispose();
  24035. }
  24036. while (this.highlightLayers.length) {
  24037. this.highlightLayers[0].dispose();
  24038. }
  24039. // Release textures
  24040. while (this.textures.length) {
  24041. this.textures[0].dispose();
  24042. }
  24043. // Release UBO
  24044. this._sceneUbo.dispose();
  24045. if (this._alternateSceneUbo) {
  24046. this._alternateSceneUbo.dispose();
  24047. }
  24048. // Post-processes
  24049. this.postProcessManager.dispose();
  24050. if (this._postProcessRenderPipelineManager) {
  24051. this._postProcessRenderPipelineManager.dispose();
  24052. }
  24053. // Physics
  24054. if (this._physicsEngine) {
  24055. this.disablePhysicsEngine();
  24056. }
  24057. // Remove from engine
  24058. index = this._engine.scenes.indexOf(this);
  24059. if (index > -1) {
  24060. this._engine.scenes.splice(index, 1);
  24061. }
  24062. this._engine.wipeCaches(true);
  24063. this._isDisposed = true;
  24064. };
  24065. Object.defineProperty(Scene.prototype, "isDisposed", {
  24066. get: function () {
  24067. return this._isDisposed;
  24068. },
  24069. enumerable: true,
  24070. configurable: true
  24071. });
  24072. // Release sounds & sounds tracks
  24073. Scene.prototype.disposeSounds = function () {
  24074. if (!this._mainSoundTrack) {
  24075. return;
  24076. }
  24077. this.mainSoundTrack.dispose();
  24078. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24079. this.soundTracks[scIndex].dispose();
  24080. }
  24081. };
  24082. // Octrees
  24083. Scene.prototype.getWorldExtends = function () {
  24084. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24085. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24086. for (var index = 0; index < this.meshes.length; index++) {
  24087. var mesh = this.meshes[index];
  24088. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24089. continue;
  24090. }
  24091. mesh.computeWorldMatrix(true);
  24092. var boundingInfo = mesh.getBoundingInfo();
  24093. var minBox = boundingInfo.boundingBox.minimumWorld;
  24094. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24095. BABYLON.Tools.CheckExtends(minBox, min, max);
  24096. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24097. }
  24098. return {
  24099. min: min,
  24100. max: max
  24101. };
  24102. };
  24103. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24104. if (maxCapacity === void 0) { maxCapacity = 64; }
  24105. if (maxDepth === void 0) { maxDepth = 2; }
  24106. if (!this._selectionOctree) {
  24107. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24108. }
  24109. var worldExtends = this.getWorldExtends();
  24110. // Update octree
  24111. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24112. return this._selectionOctree;
  24113. };
  24114. // Picking
  24115. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24116. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24117. var result = BABYLON.Ray.Zero();
  24118. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24119. return result;
  24120. };
  24121. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24122. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24123. var engine = this._engine;
  24124. if (!camera) {
  24125. if (!this.activeCamera)
  24126. throw new Error("Active camera not set");
  24127. camera = this.activeCamera;
  24128. }
  24129. var cameraViewport = camera.viewport;
  24130. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24131. // Moving coordinates to local viewport world
  24132. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24133. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24134. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24135. return this;
  24136. };
  24137. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24138. var result = BABYLON.Ray.Zero();
  24139. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24140. return result;
  24141. };
  24142. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24143. if (!BABYLON.PickingInfo) {
  24144. return this;
  24145. }
  24146. var engine = this._engine;
  24147. if (!camera) {
  24148. if (!this.activeCamera)
  24149. throw new Error("Active camera not set");
  24150. camera = this.activeCamera;
  24151. }
  24152. var cameraViewport = camera.viewport;
  24153. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24154. var identity = BABYLON.Matrix.Identity();
  24155. // Moving coordinates to local viewport world
  24156. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24157. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24158. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24159. return this;
  24160. };
  24161. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24162. if (!BABYLON.PickingInfo) {
  24163. return null;
  24164. }
  24165. var pickingInfo = null;
  24166. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24167. var mesh = this.meshes[meshIndex];
  24168. if (predicate) {
  24169. if (!predicate(mesh)) {
  24170. continue;
  24171. }
  24172. }
  24173. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24174. continue;
  24175. }
  24176. var world = mesh.getWorldMatrix();
  24177. var ray = rayFunction(world);
  24178. var result = mesh.intersects(ray, fastCheck);
  24179. if (!result || !result.hit)
  24180. continue;
  24181. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24182. continue;
  24183. pickingInfo = result;
  24184. if (fastCheck) {
  24185. break;
  24186. }
  24187. }
  24188. return pickingInfo || new BABYLON.PickingInfo();
  24189. };
  24190. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  24191. if (!BABYLON.PickingInfo) {
  24192. return null;
  24193. }
  24194. var pickingInfos = new Array();
  24195. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24196. var mesh = this.meshes[meshIndex];
  24197. if (predicate) {
  24198. if (!predicate(mesh)) {
  24199. continue;
  24200. }
  24201. }
  24202. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24203. continue;
  24204. }
  24205. var world = mesh.getWorldMatrix();
  24206. var ray = rayFunction(world);
  24207. var result = mesh.intersects(ray, false);
  24208. if (!result || !result.hit)
  24209. continue;
  24210. pickingInfos.push(result);
  24211. }
  24212. return pickingInfos;
  24213. };
  24214. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  24215. if (!BABYLON.PickingInfo) {
  24216. return null;
  24217. }
  24218. var pickingInfo = null;
  24219. if (!camera) {
  24220. if (!this.activeCamera) {
  24221. return null;
  24222. }
  24223. camera = this.activeCamera;
  24224. }
  24225. if (this.spriteManagers.length > 0) {
  24226. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  24227. var spriteManager = this.spriteManagers[spriteIndex];
  24228. if (!spriteManager.isPickable) {
  24229. continue;
  24230. }
  24231. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  24232. if (!result || !result.hit)
  24233. continue;
  24234. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24235. continue;
  24236. pickingInfo = result;
  24237. if (fastCheck) {
  24238. break;
  24239. }
  24240. }
  24241. }
  24242. return pickingInfo || new BABYLON.PickingInfo();
  24243. };
  24244. /** Launch a ray to try to pick a mesh in the scene
  24245. * @param x position on screen
  24246. * @param y position on screen
  24247. * @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
  24248. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24249. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24250. */
  24251. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  24252. var _this = this;
  24253. if (!BABYLON.PickingInfo) {
  24254. return null;
  24255. }
  24256. return this._internalPick(function (world) {
  24257. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  24258. return _this._tempPickingRay;
  24259. }, predicate, fastCheck);
  24260. };
  24261. /** Launch a ray to try to pick a sprite in the scene
  24262. * @param x position on screen
  24263. * @param y position on screen
  24264. * @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
  24265. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24266. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24267. */
  24268. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  24269. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  24270. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  24271. };
  24272. /** Use the given ray to pick a mesh in the scene
  24273. * @param ray The ray to use to pick meshes
  24274. * @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
  24275. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24276. */
  24277. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  24278. var _this = this;
  24279. return this._internalPick(function (world) {
  24280. if (!_this._pickWithRayInverseMatrix) {
  24281. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24282. }
  24283. world.invertToRef(_this._pickWithRayInverseMatrix);
  24284. if (!_this._cachedRayForTransform) {
  24285. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24286. }
  24287. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24288. return _this._cachedRayForTransform;
  24289. }, predicate, fastCheck);
  24290. };
  24291. /**
  24292. * Launch a ray to try to pick a mesh in the scene
  24293. * @param x X position on screen
  24294. * @param y Y position on screen
  24295. * @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
  24296. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24297. */
  24298. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  24299. var _this = this;
  24300. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  24301. };
  24302. /**
  24303. * Launch a ray to try to pick a mesh in the scene
  24304. * @param ray Ray to use
  24305. * @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
  24306. */
  24307. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  24308. var _this = this;
  24309. return this._internalMultiPick(function (world) {
  24310. if (!_this._pickWithRayInverseMatrix) {
  24311. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24312. }
  24313. world.invertToRef(_this._pickWithRayInverseMatrix);
  24314. if (!_this._cachedRayForTransform) {
  24315. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24316. }
  24317. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24318. return _this._cachedRayForTransform;
  24319. }, predicate);
  24320. };
  24321. Scene.prototype.setPointerOverMesh = function (mesh) {
  24322. if (this._pointerOverMesh === mesh) {
  24323. return;
  24324. }
  24325. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24326. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24327. }
  24328. this._pointerOverMesh = mesh;
  24329. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24330. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24331. }
  24332. };
  24333. Scene.prototype.getPointerOverMesh = function () {
  24334. return this._pointerOverMesh;
  24335. };
  24336. Scene.prototype.setPointerOverSprite = function (sprite) {
  24337. if (this._pointerOverSprite === sprite) {
  24338. return;
  24339. }
  24340. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24341. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24342. }
  24343. this._pointerOverSprite = sprite;
  24344. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24345. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24346. }
  24347. };
  24348. Scene.prototype.getPointerOverSprite = function () {
  24349. return this._pointerOverSprite;
  24350. };
  24351. // Physics
  24352. Scene.prototype.getPhysicsEngine = function () {
  24353. return this._physicsEngine;
  24354. };
  24355. /**
  24356. * Enables physics to the current scene
  24357. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  24358. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  24359. * @return {boolean} was the physics engine initialized
  24360. */
  24361. Scene.prototype.enablePhysics = function (gravity, plugin) {
  24362. if (gravity === void 0) { gravity = null; }
  24363. if (this._physicsEngine) {
  24364. return true;
  24365. }
  24366. try {
  24367. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  24368. return true;
  24369. }
  24370. catch (e) {
  24371. BABYLON.Tools.Error(e.message);
  24372. return false;
  24373. }
  24374. };
  24375. Scene.prototype.disablePhysicsEngine = function () {
  24376. if (!this._physicsEngine) {
  24377. return;
  24378. }
  24379. this._physicsEngine.dispose();
  24380. this._physicsEngine = null;
  24381. };
  24382. Scene.prototype.isPhysicsEnabled = function () {
  24383. return this._physicsEngine !== undefined;
  24384. };
  24385. Scene.prototype.deleteCompoundImpostor = function (compound) {
  24386. var mesh = compound.parts[0].mesh;
  24387. if (mesh.physicsImpostor) {
  24388. mesh.physicsImpostor.dispose();
  24389. mesh.physicsImpostor = null;
  24390. }
  24391. };
  24392. // Misc.
  24393. Scene.prototype._rebuildGeometries = function () {
  24394. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  24395. var geometry = _a[_i];
  24396. geometry._rebuild();
  24397. }
  24398. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  24399. var mesh = _c[_b];
  24400. mesh._rebuild();
  24401. }
  24402. if (this.postProcessManager) {
  24403. this.postProcessManager._rebuild();
  24404. }
  24405. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  24406. var layer = _e[_d];
  24407. layer._rebuild();
  24408. }
  24409. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  24410. var highlightLayer = _g[_f];
  24411. highlightLayer._rebuild();
  24412. }
  24413. if (this._boundingBoxRenderer) {
  24414. this._boundingBoxRenderer._rebuild();
  24415. }
  24416. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  24417. var system = _j[_h];
  24418. system.rebuild();
  24419. }
  24420. if (this._postProcessRenderPipelineManager) {
  24421. this._postProcessRenderPipelineManager._rebuild();
  24422. }
  24423. };
  24424. Scene.prototype._rebuildTextures = function () {
  24425. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  24426. var texture = _a[_i];
  24427. texture._rebuild();
  24428. }
  24429. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24430. };
  24431. /**
  24432. * Creates a default light for the scene.
  24433. * @param replace Whether to replace the existing lights in the scene.
  24434. */
  24435. Scene.prototype.createDefaultLight = function (replace) {
  24436. if (replace === void 0) { replace = false; }
  24437. // Dispose existing light in replace mode.
  24438. if (replace) {
  24439. if (this.lights) {
  24440. for (var i = 0; i < this.lights.length; i++) {
  24441. this.lights[i].dispose();
  24442. }
  24443. }
  24444. }
  24445. // Light
  24446. if (this.lights.length === 0) {
  24447. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  24448. }
  24449. };
  24450. /**
  24451. * Creates a default camera for the scene.
  24452. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  24453. * @param replace Whether to replace the existing active camera in the scene.
  24454. * @param attachCameraControls Whether to attach camera controls to the canvas.
  24455. */
  24456. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  24457. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24458. if (replace === void 0) { replace = false; }
  24459. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24460. // Dispose existing camera in replace mode.
  24461. if (replace) {
  24462. if (this.activeCamera) {
  24463. this.activeCamera.dispose();
  24464. this.activeCamera = null;
  24465. }
  24466. }
  24467. // Camera
  24468. if (!this.activeCamera) {
  24469. var worldExtends = this.getWorldExtends();
  24470. var worldSize = worldExtends.max.subtract(worldExtends.min);
  24471. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  24472. var camera;
  24473. var radius = worldSize.length() * 1.5;
  24474. if (createArcRotateCamera) {
  24475. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  24476. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  24477. arcRotateCamera.wheelPrecision = 100 / radius;
  24478. camera = arcRotateCamera;
  24479. }
  24480. else {
  24481. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  24482. freeCamera.setTarget(worldCenter);
  24483. camera = freeCamera;
  24484. }
  24485. camera.minZ = radius * 0.01;
  24486. camera.maxZ = radius * 1000;
  24487. camera.speed = radius * 0.2;
  24488. this.activeCamera = camera;
  24489. var canvas = this.getEngine().getRenderingCanvas();
  24490. if (attachCameraControls && canvas) {
  24491. camera.attachControl(canvas);
  24492. }
  24493. }
  24494. };
  24495. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  24496. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24497. if (replace === void 0) { replace = false; }
  24498. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24499. this.createDefaultLight(replace);
  24500. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  24501. };
  24502. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  24503. if (pbr === void 0) { pbr = false; }
  24504. if (scale === void 0) { scale = 1000; }
  24505. if (blur === void 0) { blur = 0; }
  24506. if (environmentTexture) {
  24507. this.environmentTexture = environmentTexture;
  24508. }
  24509. if (!this.environmentTexture) {
  24510. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  24511. return null;
  24512. }
  24513. // Skybox
  24514. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  24515. if (pbr) {
  24516. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  24517. hdrSkyboxMaterial.backFaceCulling = false;
  24518. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24519. if (hdrSkyboxMaterial.reflectionTexture) {
  24520. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24521. }
  24522. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  24523. hdrSkyboxMaterial.disableLighting = true;
  24524. hdrSkyboxMaterial.twoSidedLighting = true;
  24525. hdrSkybox.infiniteDistance = true;
  24526. hdrSkybox.material = hdrSkyboxMaterial;
  24527. }
  24528. else {
  24529. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  24530. skyboxMaterial.backFaceCulling = false;
  24531. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24532. if (skyboxMaterial.reflectionTexture) {
  24533. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24534. }
  24535. skyboxMaterial.disableLighting = true;
  24536. hdrSkybox.infiniteDistance = true;
  24537. hdrSkybox.material = skyboxMaterial;
  24538. }
  24539. return hdrSkybox;
  24540. };
  24541. Scene.prototype.createDefaultEnvironment = function (options) {
  24542. if (BABYLON.EnvironmentHelper) {
  24543. return new BABYLON.EnvironmentHelper(options, this);
  24544. }
  24545. return null;
  24546. };
  24547. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  24548. if (webVROptions === void 0) { webVROptions = {}; }
  24549. return new BABYLON.VRExperienceHelper(this, webVROptions);
  24550. };
  24551. // Tags
  24552. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  24553. if (tagsQuery === undefined) {
  24554. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  24555. return list;
  24556. }
  24557. var listByTags = [];
  24558. forEach = forEach || (function (item) { return; });
  24559. for (var i in list) {
  24560. var item = list[i];
  24561. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  24562. listByTags.push(item);
  24563. forEach(item);
  24564. }
  24565. }
  24566. return listByTags;
  24567. };
  24568. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  24569. return this._getByTags(this.meshes, tagsQuery, forEach);
  24570. };
  24571. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  24572. return this._getByTags(this.cameras, tagsQuery, forEach);
  24573. };
  24574. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  24575. return this._getByTags(this.lights, tagsQuery, forEach);
  24576. };
  24577. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  24578. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  24579. };
  24580. /**
  24581. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24582. * This allowed control for front to back rendering or reversly depending of the special needs.
  24583. *
  24584. * @param renderingGroupId The rendering group id corresponding to its index
  24585. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24586. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24587. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24588. */
  24589. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24590. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24591. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24592. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24593. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  24594. };
  24595. /**
  24596. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24597. *
  24598. * @param renderingGroupId The rendering group id corresponding to its index
  24599. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24600. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24601. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24602. */
  24603. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24604. if (depth === void 0) { depth = true; }
  24605. if (stencil === void 0) { stencil = true; }
  24606. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  24607. };
  24608. /**
  24609. * Will flag all materials as dirty to trigger new shader compilation
  24610. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  24611. */
  24612. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  24613. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  24614. var material = _a[_i];
  24615. if (predicate && !predicate(material)) {
  24616. continue;
  24617. }
  24618. material.markAsDirty(flag);
  24619. }
  24620. };
  24621. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  24622. var _this = this;
  24623. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  24624. this._activeRequests.push(request);
  24625. request.onCompleteObservable.add(function (request) {
  24626. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  24627. });
  24628. return request;
  24629. };
  24630. /** @ignore */
  24631. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  24632. var _this = this;
  24633. return new Promise(function (resolve, reject) {
  24634. _this._loadFile(url, function (data) {
  24635. resolve(data);
  24636. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  24637. reject(exception);
  24638. });
  24639. });
  24640. };
  24641. // Statics
  24642. Scene._FOGMODE_NONE = 0;
  24643. Scene._FOGMODE_EXP = 1;
  24644. Scene._FOGMODE_EXP2 = 2;
  24645. Scene._FOGMODE_LINEAR = 3;
  24646. Scene._uniqueIdCounter = 0;
  24647. Scene.MinDeltaTime = 1.0;
  24648. Scene.MaxDeltaTime = 1000.0;
  24649. /** The distance in pixel that you have to move to prevent some events */
  24650. Scene.DragMovementThreshold = 10; // in pixels
  24651. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  24652. Scene.LongPressDelay = 500; // in milliseconds
  24653. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  24654. Scene.DoubleClickDelay = 300; // in milliseconds
  24655. /** If you need to check double click without raising a single click at first click, enable this flag */
  24656. Scene.ExclusiveDoubleClickMode = false;
  24657. return Scene;
  24658. }());
  24659. BABYLON.Scene = Scene;
  24660. })(BABYLON || (BABYLON = {}));
  24661. //# sourceMappingURL=babylon.scene.js.map
  24662. var BABYLON;
  24663. (function (BABYLON) {
  24664. /**
  24665. * Set of assets to keep when moving a scene into an asset container.
  24666. */
  24667. var KeepAssets = /** @class */ (function () {
  24668. function KeepAssets() {
  24669. /**
  24670. * Cameras to keep.
  24671. */
  24672. this.cameras = new Array();
  24673. /**
  24674. * Lights to keep.
  24675. */
  24676. this.lights = new Array();
  24677. /**
  24678. * Meshes to keep.
  24679. */
  24680. this.meshes = new Array();
  24681. /**
  24682. * Skeletons to keep.
  24683. */
  24684. this.skeletons = new Array();
  24685. /**
  24686. * ParticleSystems to keep.
  24687. */
  24688. this.particleSystems = new Array();
  24689. /**
  24690. * Animations to keep.
  24691. */
  24692. this.animations = new Array();
  24693. /**
  24694. * MultiMaterials to keep.
  24695. */
  24696. this.multiMaterials = new Array();
  24697. /**
  24698. * Materials to keep.
  24699. */
  24700. this.materials = new Array();
  24701. /**
  24702. * MorphTargetManagers to keep.
  24703. */
  24704. this.morphTargetManagers = new Array();
  24705. /**
  24706. * Geometries to keep.
  24707. */
  24708. this.geometries = new Array();
  24709. /**
  24710. * TransformNodes to keep.
  24711. */
  24712. this.transformNodes = new Array();
  24713. /**
  24714. * LensFlareSystems to keep.
  24715. */
  24716. this.lensFlareSystems = new Array();
  24717. /**
  24718. * ShadowGenerators to keep.
  24719. */
  24720. this.shadowGenerators = new Array();
  24721. /**
  24722. * ActionManagers to keep.
  24723. */
  24724. this.actionManagers = new Array();
  24725. /**
  24726. * Sounds to keep.
  24727. */
  24728. this.sounds = new Array();
  24729. }
  24730. return KeepAssets;
  24731. }());
  24732. BABYLON.KeepAssets = KeepAssets;
  24733. /**
  24734. * Container with a set of assets that can be added or removed from a scene.
  24735. */
  24736. var AssetContainer = /** @class */ (function () {
  24737. /**
  24738. * Instantiates an AssetContainer.
  24739. * @param scene The scene the AssetContainer belongs to.
  24740. */
  24741. function AssetContainer(scene) {
  24742. // Objects
  24743. /**
  24744. * Cameras populated in the container.
  24745. */
  24746. this.cameras = new Array();
  24747. /**
  24748. * Lights populated in the container.
  24749. */
  24750. this.lights = new Array();
  24751. /**
  24752. * Meshes populated in the container.
  24753. */
  24754. this.meshes = new Array();
  24755. /**
  24756. * Skeletons populated in the container.
  24757. */
  24758. this.skeletons = new Array();
  24759. /**
  24760. * ParticleSystems populated in the container.
  24761. */
  24762. this.particleSystems = new Array();
  24763. /**
  24764. * Animations populated in the container.
  24765. */
  24766. this.animations = new Array();
  24767. /**
  24768. * MultiMaterials populated in the container.
  24769. */
  24770. this.multiMaterials = new Array();
  24771. /**
  24772. * Materials populated in the container.
  24773. */
  24774. this.materials = new Array();
  24775. /**
  24776. * MorphTargetManagers populated in the container.
  24777. */
  24778. this.morphTargetManagers = new Array();
  24779. /**
  24780. * Geometries populated in the container.
  24781. */
  24782. this.geometries = new Array();
  24783. /**
  24784. * TransformNodes populated in the container.
  24785. */
  24786. this.transformNodes = new Array();
  24787. /**
  24788. * LensFlareSystems populated in the container.
  24789. */
  24790. this.lensFlareSystems = new Array();
  24791. /**
  24792. * ShadowGenerators populated in the container.
  24793. */
  24794. this.shadowGenerators = new Array();
  24795. /**
  24796. * ActionManagers populated in the container.
  24797. */
  24798. this.actionManagers = new Array();
  24799. /**
  24800. * Sounds populated in the container.
  24801. */
  24802. this.sounds = new Array();
  24803. this.scene = scene;
  24804. }
  24805. /**
  24806. * Adds all the assets from the container to the scene.
  24807. */
  24808. AssetContainer.prototype.addAllToScene = function () {
  24809. var _this = this;
  24810. this.cameras.forEach(function (o) {
  24811. _this.scene.addCamera(o);
  24812. });
  24813. this.lights.forEach(function (o) {
  24814. _this.scene.addLight(o);
  24815. });
  24816. this.meshes.forEach(function (o) {
  24817. _this.scene.addMesh(o);
  24818. });
  24819. this.skeletons.forEach(function (o) {
  24820. _this.scene.addSkeleton(o);
  24821. });
  24822. this.particleSystems.forEach(function (o) {
  24823. _this.scene.addParticleSystem(o);
  24824. });
  24825. this.animations.forEach(function (o) {
  24826. _this.scene.addAnimation(o);
  24827. });
  24828. this.multiMaterials.forEach(function (o) {
  24829. _this.scene.addMultiMaterial(o);
  24830. });
  24831. this.materials.forEach(function (o) {
  24832. _this.scene.addMaterial(o);
  24833. });
  24834. this.morphTargetManagers.forEach(function (o) {
  24835. _this.scene.addMorphTargetManager(o);
  24836. });
  24837. this.geometries.forEach(function (o) {
  24838. _this.scene.addGeometry(o);
  24839. });
  24840. this.transformNodes.forEach(function (o) {
  24841. _this.scene.addTransformNode(o);
  24842. });
  24843. this.lensFlareSystems.forEach(function (o) {
  24844. _this.scene.addLensFlareSystem(o);
  24845. });
  24846. this.actionManagers.forEach(function (o) {
  24847. _this.scene.addActionManager(o);
  24848. });
  24849. this.sounds.forEach(function (o) {
  24850. o.play();
  24851. o.autoplay = true;
  24852. _this.scene.mainSoundTrack.AddSound(o);
  24853. });
  24854. };
  24855. /**
  24856. * Removes all the assets in the container from the scene
  24857. */
  24858. AssetContainer.prototype.removeAllFromScene = function () {
  24859. var _this = this;
  24860. this.cameras.forEach(function (o) {
  24861. _this.scene.removeCamera(o);
  24862. });
  24863. this.lights.forEach(function (o) {
  24864. _this.scene.removeLight(o);
  24865. });
  24866. this.meshes.forEach(function (o) {
  24867. _this.scene.removeMesh(o);
  24868. });
  24869. this.skeletons.forEach(function (o) {
  24870. _this.scene.removeSkeleton(o);
  24871. });
  24872. this.particleSystems.forEach(function (o) {
  24873. _this.scene.removeParticleSystem(o);
  24874. });
  24875. this.animations.forEach(function (o) {
  24876. _this.scene.removeAnimation(o);
  24877. });
  24878. this.multiMaterials.forEach(function (o) {
  24879. _this.scene.removeMultiMaterial(o);
  24880. });
  24881. this.materials.forEach(function (o) {
  24882. _this.scene.removeMaterial(o);
  24883. });
  24884. this.morphTargetManagers.forEach(function (o) {
  24885. _this.scene.removeMorphTargetManager(o);
  24886. });
  24887. this.geometries.forEach(function (o) {
  24888. _this.scene.removeGeometry(o);
  24889. });
  24890. this.transformNodes.forEach(function (o) {
  24891. _this.scene.removeTransformNode(o);
  24892. });
  24893. this.lensFlareSystems.forEach(function (o) {
  24894. _this.scene.removeLensFlareSystem(o);
  24895. });
  24896. this.actionManagers.forEach(function (o) {
  24897. _this.scene.removeActionManager(o);
  24898. });
  24899. this.sounds.forEach(function (o) {
  24900. o.stop();
  24901. o.autoplay = false;
  24902. _this.scene.mainSoundTrack.RemoveSound(o);
  24903. });
  24904. };
  24905. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  24906. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  24907. var asset = sourceAssets_1[_i];
  24908. var move = true;
  24909. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  24910. var keepAsset = keepAssets_1[_a];
  24911. if (asset === keepAsset) {
  24912. move = false;
  24913. break;
  24914. }
  24915. }
  24916. if (move) {
  24917. targetAssets.push(asset);
  24918. }
  24919. }
  24920. };
  24921. /**
  24922. * Removes all the assets contained in the scene and adds them to the container.
  24923. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  24924. */
  24925. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  24926. if (keepAssets === undefined) {
  24927. keepAssets = new KeepAssets();
  24928. }
  24929. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  24930. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  24931. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  24932. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  24933. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  24934. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  24935. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  24936. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  24937. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  24938. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  24939. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  24940. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  24941. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  24942. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  24943. this.removeAllFromScene();
  24944. };
  24945. return AssetContainer;
  24946. }());
  24947. BABYLON.AssetContainer = AssetContainer;
  24948. })(BABYLON || (BABYLON = {}));
  24949. //# sourceMappingURL=babylon.assetContainer.js.map
  24950. var BABYLON;
  24951. (function (BABYLON) {
  24952. var Buffer = /** @class */ (function () {
  24953. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  24954. if (instanced === void 0) { instanced = false; }
  24955. if (engine instanceof BABYLON.Mesh) {
  24956. this._engine = engine.getScene().getEngine();
  24957. }
  24958. else {
  24959. this._engine = engine;
  24960. }
  24961. this._updatable = updatable;
  24962. this._data = data;
  24963. this._strideSize = stride;
  24964. if (!postponeInternalCreation) {
  24965. this.create();
  24966. }
  24967. this._instanced = instanced;
  24968. this._instanceDivisor = instanced ? 1 : 0;
  24969. }
  24970. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  24971. // a lot of these parameters are ignored as they are overriden by the buffer
  24972. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  24973. };
  24974. // Properties
  24975. Buffer.prototype.isUpdatable = function () {
  24976. return this._updatable;
  24977. };
  24978. Buffer.prototype.getData = function () {
  24979. return this._data;
  24980. };
  24981. Buffer.prototype.getBuffer = function () {
  24982. return this._buffer;
  24983. };
  24984. Buffer.prototype.getStrideSize = function () {
  24985. return this._strideSize;
  24986. };
  24987. Buffer.prototype.getIsInstanced = function () {
  24988. return this._instanced;
  24989. };
  24990. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  24991. get: function () {
  24992. return this._instanceDivisor;
  24993. },
  24994. set: function (value) {
  24995. this._instanceDivisor = value;
  24996. if (value == 0) {
  24997. this._instanced = false;
  24998. }
  24999. else {
  25000. this._instanced = true;
  25001. }
  25002. },
  25003. enumerable: true,
  25004. configurable: true
  25005. });
  25006. // Methods
  25007. Buffer.prototype.create = function (data) {
  25008. if (data === void 0) { data = null; }
  25009. if (!data && this._buffer) {
  25010. return; // nothing to do
  25011. }
  25012. data = data || this._data;
  25013. if (!data) {
  25014. return;
  25015. }
  25016. if (!this._buffer) {
  25017. if (this._updatable) {
  25018. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25019. this._data = data;
  25020. }
  25021. else {
  25022. this._buffer = this._engine.createVertexBuffer(data);
  25023. }
  25024. }
  25025. else if (this._updatable) {
  25026. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25027. this._data = data;
  25028. }
  25029. };
  25030. Buffer.prototype._rebuild = function () {
  25031. this._buffer = null;
  25032. this.create(this._data);
  25033. };
  25034. Buffer.prototype.update = function (data) {
  25035. this.create(data);
  25036. };
  25037. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25038. if (!this._buffer) {
  25039. return;
  25040. }
  25041. if (this._updatable) {
  25042. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25043. this._data = null;
  25044. }
  25045. };
  25046. Buffer.prototype.dispose = function () {
  25047. if (!this._buffer) {
  25048. return;
  25049. }
  25050. if (this._engine._releaseBuffer(this._buffer)) {
  25051. this._buffer = null;
  25052. }
  25053. };
  25054. return Buffer;
  25055. }());
  25056. BABYLON.Buffer = Buffer;
  25057. })(BABYLON || (BABYLON = {}));
  25058. //# sourceMappingURL=babylon.buffer.js.map
  25059. var BABYLON;
  25060. (function (BABYLON) {
  25061. var VertexBuffer = /** @class */ (function () {
  25062. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25063. if (!stride) {
  25064. // Deduce stride from kind
  25065. switch (kind) {
  25066. case VertexBuffer.PositionKind:
  25067. stride = 3;
  25068. break;
  25069. case VertexBuffer.NormalKind:
  25070. stride = 3;
  25071. break;
  25072. case VertexBuffer.UVKind:
  25073. case VertexBuffer.UV2Kind:
  25074. case VertexBuffer.UV3Kind:
  25075. case VertexBuffer.UV4Kind:
  25076. case VertexBuffer.UV5Kind:
  25077. case VertexBuffer.UV6Kind:
  25078. stride = 2;
  25079. break;
  25080. case VertexBuffer.TangentKind:
  25081. case VertexBuffer.ColorKind:
  25082. stride = 4;
  25083. break;
  25084. case VertexBuffer.MatricesIndicesKind:
  25085. case VertexBuffer.MatricesIndicesExtraKind:
  25086. stride = 4;
  25087. break;
  25088. case VertexBuffer.MatricesWeightsKind:
  25089. case VertexBuffer.MatricesWeightsExtraKind:
  25090. default:
  25091. stride = 4;
  25092. break;
  25093. }
  25094. }
  25095. if (data instanceof BABYLON.Buffer) {
  25096. if (!stride) {
  25097. stride = data.getStrideSize();
  25098. }
  25099. this._buffer = data;
  25100. this._ownsBuffer = false;
  25101. }
  25102. else {
  25103. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25104. this._ownsBuffer = true;
  25105. }
  25106. this._stride = stride;
  25107. this._offset = offset ? offset : 0;
  25108. this._size = size ? size : stride;
  25109. this._kind = kind;
  25110. }
  25111. VertexBuffer.prototype._rebuild = function () {
  25112. if (!this._buffer) {
  25113. return;
  25114. }
  25115. this._buffer._rebuild();
  25116. };
  25117. /**
  25118. * Returns the kind of the VertexBuffer (string).
  25119. */
  25120. VertexBuffer.prototype.getKind = function () {
  25121. return this._kind;
  25122. };
  25123. // Properties
  25124. /**
  25125. * Boolean : is the VertexBuffer updatable ?
  25126. */
  25127. VertexBuffer.prototype.isUpdatable = function () {
  25128. return this._buffer.isUpdatable();
  25129. };
  25130. /**
  25131. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25132. */
  25133. VertexBuffer.prototype.getData = function () {
  25134. return this._buffer.getData();
  25135. };
  25136. /**
  25137. * Returns the WebGLBuffer associated to the VertexBuffer.
  25138. */
  25139. VertexBuffer.prototype.getBuffer = function () {
  25140. return this._buffer.getBuffer();
  25141. };
  25142. /**
  25143. * Returns the stride of the VertexBuffer (integer).
  25144. */
  25145. VertexBuffer.prototype.getStrideSize = function () {
  25146. return this._stride;
  25147. };
  25148. /**
  25149. * Returns the offset (integer).
  25150. */
  25151. VertexBuffer.prototype.getOffset = function () {
  25152. return this._offset;
  25153. };
  25154. /**
  25155. * Returns the VertexBuffer total size (integer).
  25156. */
  25157. VertexBuffer.prototype.getSize = function () {
  25158. return this._size;
  25159. };
  25160. /**
  25161. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25162. */
  25163. VertexBuffer.prototype.getIsInstanced = function () {
  25164. return this._buffer.getIsInstanced();
  25165. };
  25166. /**
  25167. * Returns the instancing divisor, zero for non-instanced (integer).
  25168. */
  25169. VertexBuffer.prototype.getInstanceDivisor = function () {
  25170. return this._buffer.instanceDivisor;
  25171. };
  25172. // Methods
  25173. /**
  25174. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25175. * Returns the created WebGLBuffer.
  25176. */
  25177. VertexBuffer.prototype.create = function (data) {
  25178. return this._buffer.create(data);
  25179. };
  25180. /**
  25181. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25182. * This function will create a new buffer if the current one is not updatable
  25183. * Returns the updated WebGLBuffer.
  25184. */
  25185. VertexBuffer.prototype.update = function (data) {
  25186. return this._buffer.update(data);
  25187. };
  25188. /**
  25189. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25190. * Returns the directly updated WebGLBuffer.
  25191. */
  25192. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  25193. return this._buffer.updateDirectly(data, offset);
  25194. };
  25195. /**
  25196. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  25197. */
  25198. VertexBuffer.prototype.dispose = function () {
  25199. if (this._ownsBuffer) {
  25200. this._buffer.dispose();
  25201. }
  25202. };
  25203. Object.defineProperty(VertexBuffer, "PositionKind", {
  25204. get: function () {
  25205. return VertexBuffer._PositionKind;
  25206. },
  25207. enumerable: true,
  25208. configurable: true
  25209. });
  25210. Object.defineProperty(VertexBuffer, "NormalKind", {
  25211. get: function () {
  25212. return VertexBuffer._NormalKind;
  25213. },
  25214. enumerable: true,
  25215. configurable: true
  25216. });
  25217. Object.defineProperty(VertexBuffer, "TangentKind", {
  25218. get: function () {
  25219. return VertexBuffer._TangentKind;
  25220. },
  25221. enumerable: true,
  25222. configurable: true
  25223. });
  25224. Object.defineProperty(VertexBuffer, "UVKind", {
  25225. get: function () {
  25226. return VertexBuffer._UVKind;
  25227. },
  25228. enumerable: true,
  25229. configurable: true
  25230. });
  25231. Object.defineProperty(VertexBuffer, "UV2Kind", {
  25232. get: function () {
  25233. return VertexBuffer._UV2Kind;
  25234. },
  25235. enumerable: true,
  25236. configurable: true
  25237. });
  25238. Object.defineProperty(VertexBuffer, "UV3Kind", {
  25239. get: function () {
  25240. return VertexBuffer._UV3Kind;
  25241. },
  25242. enumerable: true,
  25243. configurable: true
  25244. });
  25245. Object.defineProperty(VertexBuffer, "UV4Kind", {
  25246. get: function () {
  25247. return VertexBuffer._UV4Kind;
  25248. },
  25249. enumerable: true,
  25250. configurable: true
  25251. });
  25252. Object.defineProperty(VertexBuffer, "UV5Kind", {
  25253. get: function () {
  25254. return VertexBuffer._UV5Kind;
  25255. },
  25256. enumerable: true,
  25257. configurable: true
  25258. });
  25259. Object.defineProperty(VertexBuffer, "UV6Kind", {
  25260. get: function () {
  25261. return VertexBuffer._UV6Kind;
  25262. },
  25263. enumerable: true,
  25264. configurable: true
  25265. });
  25266. Object.defineProperty(VertexBuffer, "ColorKind", {
  25267. get: function () {
  25268. return VertexBuffer._ColorKind;
  25269. },
  25270. enumerable: true,
  25271. configurable: true
  25272. });
  25273. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  25274. get: function () {
  25275. return VertexBuffer._MatricesIndicesKind;
  25276. },
  25277. enumerable: true,
  25278. configurable: true
  25279. });
  25280. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  25281. get: function () {
  25282. return VertexBuffer._MatricesWeightsKind;
  25283. },
  25284. enumerable: true,
  25285. configurable: true
  25286. });
  25287. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  25288. get: function () {
  25289. return VertexBuffer._MatricesIndicesExtraKind;
  25290. },
  25291. enumerable: true,
  25292. configurable: true
  25293. });
  25294. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  25295. get: function () {
  25296. return VertexBuffer._MatricesWeightsExtraKind;
  25297. },
  25298. enumerable: true,
  25299. configurable: true
  25300. });
  25301. // Enums
  25302. VertexBuffer._PositionKind = "position";
  25303. VertexBuffer._NormalKind = "normal";
  25304. VertexBuffer._TangentKind = "tangent";
  25305. VertexBuffer._UVKind = "uv";
  25306. VertexBuffer._UV2Kind = "uv2";
  25307. VertexBuffer._UV3Kind = "uv3";
  25308. VertexBuffer._UV4Kind = "uv4";
  25309. VertexBuffer._UV5Kind = "uv5";
  25310. VertexBuffer._UV6Kind = "uv6";
  25311. VertexBuffer._ColorKind = "color";
  25312. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  25313. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  25314. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  25315. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  25316. return VertexBuffer;
  25317. }());
  25318. BABYLON.VertexBuffer = VertexBuffer;
  25319. })(BABYLON || (BABYLON = {}));
  25320. //# sourceMappingURL=babylon.vertexBuffer.js.map
  25321. var BABYLON;
  25322. (function (BABYLON) {
  25323. /**
  25324. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  25325. */
  25326. var DummyInternalTextureTracker = /** @class */ (function () {
  25327. function DummyInternalTextureTracker() {
  25328. /**
  25329. * Gets or set the previous tracker in the list
  25330. */
  25331. this.previous = null;
  25332. /**
  25333. * Gets or set the next tracker in the list
  25334. */
  25335. this.next = null;
  25336. }
  25337. return DummyInternalTextureTracker;
  25338. }());
  25339. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  25340. })(BABYLON || (BABYLON = {}));
  25341. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  25342. var BABYLON;
  25343. (function (BABYLON) {
  25344. /**
  25345. * Class used to store data associated with WebGL texture data for the engine
  25346. * This class should not be used directly
  25347. */
  25348. var InternalTexture = /** @class */ (function () {
  25349. /**
  25350. * Creates a new InternalTexture
  25351. * @param engine defines the engine to use
  25352. * @param dataSource defines the type of data that will be used
  25353. */
  25354. function InternalTexture(engine, dataSource) {
  25355. /**
  25356. * Observable called when the texture is loaded
  25357. */
  25358. this.onLoadedObservable = new BABYLON.Observable();
  25359. /**
  25360. * Gets or set the previous tracker in the list
  25361. */
  25362. this.previous = null;
  25363. /**
  25364. * Gets or set the next tracker in the list
  25365. */
  25366. this.next = null;
  25367. // Private
  25368. /** @ignore */
  25369. this._initialSlot = -1;
  25370. /** @ignore */
  25371. this._designatedSlot = -1;
  25372. /** @ignore */
  25373. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  25374. /** @ignore */
  25375. this._references = 1;
  25376. this._engine = engine;
  25377. this._dataSource = dataSource;
  25378. this._webGLTexture = engine._createTexture();
  25379. }
  25380. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  25381. /**
  25382. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  25383. */
  25384. get: function () {
  25385. return this._dataSource;
  25386. },
  25387. enumerable: true,
  25388. configurable: true
  25389. });
  25390. /**
  25391. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  25392. */
  25393. InternalTexture.prototype.incrementReferences = function () {
  25394. this._references++;
  25395. };
  25396. /**
  25397. * Change the size of the texture (not the size of the content)
  25398. * @param width defines the new width
  25399. * @param height defines the new height
  25400. * @param depth defines the new depth (1 by default)
  25401. */
  25402. InternalTexture.prototype.updateSize = function (width, height, depth) {
  25403. if (depth === void 0) { depth = 1; }
  25404. this.width = width;
  25405. this.height = height;
  25406. this.depth = depth;
  25407. this.baseWidth = width;
  25408. this.baseHeight = height;
  25409. this.baseDepth = depth;
  25410. this._size = width * height * depth;
  25411. };
  25412. /** @ignore */
  25413. InternalTexture.prototype._rebuild = function () {
  25414. var _this = this;
  25415. var proxy;
  25416. this.isReady = false;
  25417. this._cachedCoordinatesMode = null;
  25418. this._cachedWrapU = null;
  25419. this._cachedWrapV = null;
  25420. this._cachedAnisotropicFilteringLevel = null;
  25421. switch (this._dataSource) {
  25422. case InternalTexture.DATASOURCE_TEMP:
  25423. return;
  25424. case InternalTexture.DATASOURCE_URL:
  25425. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  25426. _this.isReady = true;
  25427. }, null, this._buffer, undefined, this.format);
  25428. proxy._swapAndDie(this);
  25429. return;
  25430. case InternalTexture.DATASOURCE_RAW:
  25431. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25432. proxy._swapAndDie(this);
  25433. this.isReady = true;
  25434. return;
  25435. case InternalTexture.DATASOURCE_RAW3D:
  25436. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25437. proxy._swapAndDie(this);
  25438. this.isReady = true;
  25439. return;
  25440. case InternalTexture.DATASOURCE_DYNAMIC:
  25441. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  25442. proxy._swapAndDie(this);
  25443. // The engine will make sure to update content so no need to flag it as isReady = true
  25444. return;
  25445. case InternalTexture.DATASOURCE_RENDERTARGET:
  25446. var options = new BABYLON.RenderTargetCreationOptions();
  25447. options.generateDepthBuffer = this._generateDepthBuffer;
  25448. options.generateMipMaps = this.generateMipMaps;
  25449. options.generateStencilBuffer = this._generateStencilBuffer;
  25450. options.samplingMode = this.samplingMode;
  25451. options.type = this.type;
  25452. if (this.isCube) {
  25453. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  25454. }
  25455. else {
  25456. var size = {
  25457. width: this.width,
  25458. height: this.height
  25459. };
  25460. proxy = this._engine.createRenderTargetTexture(size, options);
  25461. }
  25462. proxy._swapAndDie(this);
  25463. this.isReady = true;
  25464. return;
  25465. case InternalTexture.DATASOURCE_CUBE:
  25466. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  25467. _this.isReady = true;
  25468. }, null, this.format, this._extension);
  25469. proxy._swapAndDie(this);
  25470. return;
  25471. case InternalTexture.DATASOURCE_CUBERAW:
  25472. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25473. proxy._swapAndDie(this);
  25474. this.isReady = true;
  25475. return;
  25476. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  25477. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  25478. if (proxy) {
  25479. proxy._swapAndDie(_this);
  25480. }
  25481. _this.isReady = true;
  25482. }, null, this.format, this._extension);
  25483. return;
  25484. }
  25485. };
  25486. InternalTexture.prototype._swapAndDie = function (target) {
  25487. target._webGLTexture = this._webGLTexture;
  25488. if (this._framebuffer) {
  25489. target._framebuffer = this._framebuffer;
  25490. }
  25491. if (this._depthStencilBuffer) {
  25492. target._depthStencilBuffer = this._depthStencilBuffer;
  25493. }
  25494. if (this._lodTextureHigh) {
  25495. if (target._lodTextureHigh) {
  25496. target._lodTextureHigh.dispose();
  25497. }
  25498. target._lodTextureHigh = this._lodTextureHigh;
  25499. }
  25500. if (this._lodTextureMid) {
  25501. if (target._lodTextureMid) {
  25502. target._lodTextureMid.dispose();
  25503. }
  25504. target._lodTextureMid = this._lodTextureMid;
  25505. }
  25506. if (this._lodTextureLow) {
  25507. if (target._lodTextureLow) {
  25508. target._lodTextureLow.dispose();
  25509. }
  25510. target._lodTextureLow = this._lodTextureLow;
  25511. }
  25512. var cache = this._engine.getLoadedTexturesCache();
  25513. var index = cache.indexOf(this);
  25514. if (index !== -1) {
  25515. cache.splice(index, 1);
  25516. }
  25517. };
  25518. /**
  25519. * Dispose the current allocated resources
  25520. */
  25521. InternalTexture.prototype.dispose = function () {
  25522. if (!this._webGLTexture) {
  25523. return;
  25524. }
  25525. this._references--;
  25526. if (this._references === 0) {
  25527. this._engine._releaseTexture(this);
  25528. this._webGLTexture = null;
  25529. this.previous = null;
  25530. this.next = null;
  25531. }
  25532. };
  25533. /**
  25534. * The source of the texture data is unknown
  25535. */
  25536. InternalTexture.DATASOURCE_UNKNOWN = 0;
  25537. /**
  25538. * Texture data comes from an URL
  25539. */
  25540. InternalTexture.DATASOURCE_URL = 1;
  25541. /**
  25542. * Texture data is only used for temporary storage
  25543. */
  25544. InternalTexture.DATASOURCE_TEMP = 2;
  25545. /**
  25546. * Texture data comes from raw data (ArrayBuffer)
  25547. */
  25548. InternalTexture.DATASOURCE_RAW = 3;
  25549. /**
  25550. * Texture content is dynamic (video or dynamic texture)
  25551. */
  25552. InternalTexture.DATASOURCE_DYNAMIC = 4;
  25553. /**
  25554. * Texture content is generated by rendering to it
  25555. */
  25556. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  25557. /**
  25558. * Texture content is part of a multi render target process
  25559. */
  25560. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  25561. /**
  25562. * Texture data comes from a cube data file
  25563. */
  25564. InternalTexture.DATASOURCE_CUBE = 7;
  25565. /**
  25566. * Texture data comes from a raw cube data
  25567. */
  25568. InternalTexture.DATASOURCE_CUBERAW = 8;
  25569. /**
  25570. * Texture data come from a prefiltered cube data file
  25571. */
  25572. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  25573. /**
  25574. * Texture content is raw 3D data
  25575. */
  25576. InternalTexture.DATASOURCE_RAW3D = 10;
  25577. return InternalTexture;
  25578. }());
  25579. BABYLON.InternalTexture = InternalTexture;
  25580. })(BABYLON || (BABYLON = {}));
  25581. //# sourceMappingURL=babylon.internalTexture.js.map
  25582. var BABYLON;
  25583. (function (BABYLON) {
  25584. var BaseTexture = /** @class */ (function () {
  25585. function BaseTexture(scene) {
  25586. this._hasAlpha = false;
  25587. this.getAlphaFromRGB = false;
  25588. this.level = 1;
  25589. this.coordinatesIndex = 0;
  25590. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  25591. /*
  25592. * How a texture is mapped.
  25593. *
  25594. * | Value | Type | Description |
  25595. * | ----- | ----------------------------------- | ----------- |
  25596. * | 0 | EXPLICIT_MODE | |
  25597. * | 1 | SPHERICAL_MODE | |
  25598. * | 2 | PLANAR_MODE | |
  25599. * | 3 | CUBIC_MODE | |
  25600. * | 4 | PROJECTION_MODE | |
  25601. * | 5 | SKYBOX_MODE | |
  25602. * | 6 | INVCUBIC_MODE | |
  25603. * | 7 | EQUIRECTANGULAR_MODE | |
  25604. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  25605. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  25606. */
  25607. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  25608. /*
  25609. * | Value | Type | Description |
  25610. * | ----- | ------------------ | ----------- |
  25611. * | 0 | CLAMP_ADDRESSMODE | |
  25612. * | 1 | WRAP_ADDRESSMODE | |
  25613. * | 2 | MIRROR_ADDRESSMODE | |
  25614. */
  25615. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  25616. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  25617. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  25618. this.isCube = false;
  25619. this.is3D = false;
  25620. this.gammaSpace = true;
  25621. this.invertZ = false;
  25622. this.lodLevelInAlpha = false;
  25623. this.lodGenerationOffset = 0.0;
  25624. this.lodGenerationScale = 0.8;
  25625. this.isRenderTarget = false;
  25626. this.animations = new Array();
  25627. /**
  25628. * An event triggered when the texture is disposed.
  25629. * @type {BABYLON.Observable}
  25630. */
  25631. this.onDisposeObservable = new BABYLON.Observable();
  25632. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25633. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25634. if (this._scene) {
  25635. this._scene.textures.push(this);
  25636. }
  25637. this._uid = null;
  25638. }
  25639. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  25640. get: function () {
  25641. return this._hasAlpha;
  25642. },
  25643. set: function (value) {
  25644. if (this._hasAlpha === value) {
  25645. return;
  25646. }
  25647. this._hasAlpha = value;
  25648. if (this._scene) {
  25649. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  25650. }
  25651. },
  25652. enumerable: true,
  25653. configurable: true
  25654. });
  25655. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  25656. get: function () {
  25657. return this._coordinatesMode;
  25658. },
  25659. set: function (value) {
  25660. if (this._coordinatesMode === value) {
  25661. return;
  25662. }
  25663. this._coordinatesMode = value;
  25664. if (this._scene) {
  25665. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25666. }
  25667. },
  25668. enumerable: true,
  25669. configurable: true
  25670. });
  25671. Object.defineProperty(BaseTexture.prototype, "uid", {
  25672. get: function () {
  25673. if (!this._uid) {
  25674. this._uid = BABYLON.Tools.RandomId();
  25675. }
  25676. return this._uid;
  25677. },
  25678. enumerable: true,
  25679. configurable: true
  25680. });
  25681. BaseTexture.prototype.toString = function () {
  25682. return this.name;
  25683. };
  25684. BaseTexture.prototype.getClassName = function () {
  25685. return "BaseTexture";
  25686. };
  25687. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  25688. set: function (callback) {
  25689. if (this._onDisposeObserver) {
  25690. this.onDisposeObservable.remove(this._onDisposeObserver);
  25691. }
  25692. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25693. },
  25694. enumerable: true,
  25695. configurable: true
  25696. });
  25697. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  25698. get: function () {
  25699. return true;
  25700. },
  25701. enumerable: true,
  25702. configurable: true
  25703. });
  25704. BaseTexture.prototype.getScene = function () {
  25705. return this._scene;
  25706. };
  25707. BaseTexture.prototype.getTextureMatrix = function () {
  25708. return BABYLON.Matrix.IdentityReadOnly;
  25709. };
  25710. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  25711. return BABYLON.Matrix.IdentityReadOnly;
  25712. };
  25713. BaseTexture.prototype.getInternalTexture = function () {
  25714. return this._texture;
  25715. };
  25716. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  25717. return !this.isBlocking || this.isReady();
  25718. };
  25719. BaseTexture.prototype.isReady = function () {
  25720. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  25721. this.delayLoad();
  25722. return false;
  25723. }
  25724. if (this._texture) {
  25725. return this._texture.isReady;
  25726. }
  25727. return false;
  25728. };
  25729. BaseTexture.prototype.getSize = function () {
  25730. if (this._texture && this._texture.width) {
  25731. return new BABYLON.Size(this._texture.width, this._texture.height);
  25732. }
  25733. if (this._texture && this._texture._size) {
  25734. return new BABYLON.Size(this._texture._size, this._texture._size);
  25735. }
  25736. return BABYLON.Size.Zero();
  25737. };
  25738. BaseTexture.prototype.getBaseSize = function () {
  25739. if (!this.isReady() || !this._texture)
  25740. return BABYLON.Size.Zero();
  25741. if (this._texture._size) {
  25742. return new BABYLON.Size(this._texture._size, this._texture._size);
  25743. }
  25744. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  25745. };
  25746. BaseTexture.prototype.scale = function (ratio) {
  25747. };
  25748. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  25749. get: function () {
  25750. return false;
  25751. },
  25752. enumerable: true,
  25753. configurable: true
  25754. });
  25755. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  25756. if (!this._scene) {
  25757. return null;
  25758. }
  25759. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  25760. for (var index = 0; index < texturesCache.length; index++) {
  25761. var texturesCacheEntry = texturesCache[index];
  25762. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  25763. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  25764. texturesCacheEntry.incrementReferences();
  25765. return texturesCacheEntry;
  25766. }
  25767. }
  25768. }
  25769. return null;
  25770. };
  25771. BaseTexture.prototype._rebuild = function () {
  25772. };
  25773. BaseTexture.prototype.delayLoad = function () {
  25774. };
  25775. BaseTexture.prototype.clone = function () {
  25776. return null;
  25777. };
  25778. Object.defineProperty(BaseTexture.prototype, "textureType", {
  25779. get: function () {
  25780. if (!this._texture) {
  25781. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25782. }
  25783. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25784. },
  25785. enumerable: true,
  25786. configurable: true
  25787. });
  25788. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  25789. get: function () {
  25790. if (!this._texture) {
  25791. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25792. }
  25793. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25794. },
  25795. enumerable: true,
  25796. configurable: true
  25797. });
  25798. BaseTexture.prototype.readPixels = function (faceIndex) {
  25799. if (faceIndex === void 0) { faceIndex = 0; }
  25800. if (!this._texture) {
  25801. return null;
  25802. }
  25803. var size = this.getSize();
  25804. var scene = this.getScene();
  25805. if (!scene) {
  25806. return null;
  25807. }
  25808. var engine = scene.getEngine();
  25809. if (this._texture.isCube) {
  25810. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  25811. }
  25812. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  25813. };
  25814. BaseTexture.prototype.releaseInternalTexture = function () {
  25815. if (this._texture) {
  25816. this._texture.dispose();
  25817. this._texture = null;
  25818. }
  25819. };
  25820. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  25821. get: function () {
  25822. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  25823. return null;
  25824. }
  25825. if (!this._texture._sphericalPolynomial) {
  25826. this._texture._sphericalPolynomial =
  25827. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  25828. }
  25829. return this._texture._sphericalPolynomial;
  25830. },
  25831. set: function (value) {
  25832. if (this._texture) {
  25833. this._texture._sphericalPolynomial = value;
  25834. }
  25835. },
  25836. enumerable: true,
  25837. configurable: true
  25838. });
  25839. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  25840. get: function () {
  25841. if (this._texture) {
  25842. return this._texture._lodTextureHigh;
  25843. }
  25844. return null;
  25845. },
  25846. enumerable: true,
  25847. configurable: true
  25848. });
  25849. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  25850. get: function () {
  25851. if (this._texture) {
  25852. return this._texture._lodTextureMid;
  25853. }
  25854. return null;
  25855. },
  25856. enumerable: true,
  25857. configurable: true
  25858. });
  25859. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  25860. get: function () {
  25861. if (this._texture) {
  25862. return this._texture._lodTextureLow;
  25863. }
  25864. return null;
  25865. },
  25866. enumerable: true,
  25867. configurable: true
  25868. });
  25869. BaseTexture.prototype.dispose = function () {
  25870. if (!this._scene) {
  25871. return;
  25872. }
  25873. // Animations
  25874. this._scene.stopAnimation(this);
  25875. // Remove from scene
  25876. this._scene._removePendingData(this);
  25877. var index = this._scene.textures.indexOf(this);
  25878. if (index >= 0) {
  25879. this._scene.textures.splice(index, 1);
  25880. }
  25881. if (this._texture === undefined) {
  25882. return;
  25883. }
  25884. // Release
  25885. this.releaseInternalTexture();
  25886. // Callback
  25887. this.onDisposeObservable.notifyObservers(this);
  25888. this.onDisposeObservable.clear();
  25889. };
  25890. BaseTexture.prototype.serialize = function () {
  25891. if (!this.name) {
  25892. return null;
  25893. }
  25894. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  25895. // Animations
  25896. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  25897. return serializationObject;
  25898. };
  25899. BaseTexture.WhenAllReady = function (textures, callback) {
  25900. var numRemaining = textures.length;
  25901. if (numRemaining === 0) {
  25902. callback();
  25903. return;
  25904. }
  25905. var _loop_1 = function () {
  25906. texture = textures[i];
  25907. if (texture.isReady()) {
  25908. if (--numRemaining === 0) {
  25909. callback();
  25910. }
  25911. }
  25912. else {
  25913. onLoadObservable = texture.onLoadObservable;
  25914. var onLoadCallback_1 = function () {
  25915. onLoadObservable.removeCallback(onLoadCallback_1);
  25916. if (--numRemaining === 0) {
  25917. callback();
  25918. }
  25919. };
  25920. onLoadObservable.add(onLoadCallback_1);
  25921. }
  25922. };
  25923. var texture, onLoadObservable;
  25924. for (var i = 0; i < textures.length; i++) {
  25925. _loop_1();
  25926. }
  25927. };
  25928. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  25929. __decorate([
  25930. BABYLON.serialize()
  25931. ], BaseTexture.prototype, "name", void 0);
  25932. __decorate([
  25933. BABYLON.serialize("hasAlpha")
  25934. ], BaseTexture.prototype, "_hasAlpha", void 0);
  25935. __decorate([
  25936. BABYLON.serialize()
  25937. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  25938. __decorate([
  25939. BABYLON.serialize()
  25940. ], BaseTexture.prototype, "level", void 0);
  25941. __decorate([
  25942. BABYLON.serialize()
  25943. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  25944. __decorate([
  25945. BABYLON.serialize("coordinatesMode")
  25946. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  25947. __decorate([
  25948. BABYLON.serialize()
  25949. ], BaseTexture.prototype, "wrapU", void 0);
  25950. __decorate([
  25951. BABYLON.serialize()
  25952. ], BaseTexture.prototype, "wrapV", void 0);
  25953. __decorate([
  25954. BABYLON.serialize()
  25955. ], BaseTexture.prototype, "wrapR", void 0);
  25956. __decorate([
  25957. BABYLON.serialize()
  25958. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  25959. __decorate([
  25960. BABYLON.serialize()
  25961. ], BaseTexture.prototype, "isCube", void 0);
  25962. __decorate([
  25963. BABYLON.serialize()
  25964. ], BaseTexture.prototype, "is3D", void 0);
  25965. __decorate([
  25966. BABYLON.serialize()
  25967. ], BaseTexture.prototype, "gammaSpace", void 0);
  25968. __decorate([
  25969. BABYLON.serialize()
  25970. ], BaseTexture.prototype, "invertZ", void 0);
  25971. __decorate([
  25972. BABYLON.serialize()
  25973. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  25974. __decorate([
  25975. BABYLON.serialize()
  25976. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  25977. __decorate([
  25978. BABYLON.serialize()
  25979. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  25980. __decorate([
  25981. BABYLON.serialize()
  25982. ], BaseTexture.prototype, "isRenderTarget", void 0);
  25983. return BaseTexture;
  25984. }());
  25985. BABYLON.BaseTexture = BaseTexture;
  25986. })(BABYLON || (BABYLON = {}));
  25987. //# sourceMappingURL=babylon.baseTexture.js.map
  25988. var BABYLON;
  25989. (function (BABYLON) {
  25990. var Texture = /** @class */ (function (_super) {
  25991. __extends(Texture, _super);
  25992. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  25993. if (noMipmap === void 0) { noMipmap = false; }
  25994. if (invertY === void 0) { invertY = true; }
  25995. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25996. if (onLoad === void 0) { onLoad = null; }
  25997. if (onError === void 0) { onError = null; }
  25998. if (buffer === void 0) { buffer = null; }
  25999. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26000. var _this = _super.call(this, scene) || this;
  26001. _this.uOffset = 0;
  26002. _this.vOffset = 0;
  26003. _this.uScale = 1.0;
  26004. _this.vScale = 1.0;
  26005. _this.uAng = 0;
  26006. _this.vAng = 0;
  26007. _this.wAng = 0;
  26008. _this._isBlocking = true;
  26009. _this.name = url || "";
  26010. _this.url = url;
  26011. _this._noMipmap = noMipmap;
  26012. _this._invertY = invertY;
  26013. _this._samplingMode = samplingMode;
  26014. _this._buffer = buffer;
  26015. _this._deleteBuffer = deleteBuffer;
  26016. if (format) {
  26017. _this._format = format;
  26018. }
  26019. scene = _this.getScene();
  26020. if (!scene) {
  26021. return _this;
  26022. }
  26023. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26024. var load = function () {
  26025. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26026. _this.onLoadObservable.notifyObservers(_this);
  26027. }
  26028. if (onLoad) {
  26029. onLoad();
  26030. }
  26031. if (!_this.isBlocking && scene) {
  26032. scene.resetCachedMaterial();
  26033. }
  26034. };
  26035. if (!_this.url) {
  26036. _this._delayedOnLoad = load;
  26037. _this._delayedOnError = onError;
  26038. return _this;
  26039. }
  26040. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26041. if (!_this._texture) {
  26042. if (!scene.useDelayedTextureLoading) {
  26043. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26044. if (deleteBuffer) {
  26045. delete _this._buffer;
  26046. }
  26047. }
  26048. else {
  26049. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26050. _this._delayedOnLoad = load;
  26051. _this._delayedOnError = onError;
  26052. }
  26053. }
  26054. else {
  26055. if (_this._texture.isReady) {
  26056. BABYLON.Tools.SetImmediate(function () { return load(); });
  26057. }
  26058. else {
  26059. _this._texture.onLoadedObservable.add(load);
  26060. }
  26061. }
  26062. return _this;
  26063. }
  26064. Object.defineProperty(Texture.prototype, "noMipmap", {
  26065. get: function () {
  26066. return this._noMipmap;
  26067. },
  26068. enumerable: true,
  26069. configurable: true
  26070. });
  26071. Object.defineProperty(Texture.prototype, "isBlocking", {
  26072. get: function () {
  26073. return this._isBlocking;
  26074. },
  26075. set: function (value) {
  26076. this._isBlocking = value;
  26077. },
  26078. enumerable: true,
  26079. configurable: true
  26080. });
  26081. Object.defineProperty(Texture.prototype, "samplingMode", {
  26082. get: function () {
  26083. return this._samplingMode;
  26084. },
  26085. enumerable: true,
  26086. configurable: true
  26087. });
  26088. Texture.prototype.updateURL = function (url) {
  26089. this.url = url;
  26090. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26091. this.delayLoad();
  26092. };
  26093. Texture.prototype.delayLoad = function () {
  26094. var _this = this;
  26095. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26096. return;
  26097. }
  26098. var scene = this.getScene();
  26099. if (!scene) {
  26100. return;
  26101. }
  26102. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26103. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26104. if (!this._texture) {
  26105. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26106. if (this._deleteBuffer) {
  26107. delete this._buffer;
  26108. }
  26109. }
  26110. else {
  26111. if (this._texture.isReady) {
  26112. BABYLON.Tools.SetImmediate(function () {
  26113. if (!_this._delayedOnLoad) {
  26114. return;
  26115. }
  26116. _this._delayedOnLoad();
  26117. });
  26118. }
  26119. else {
  26120. if (this._delayedOnLoad) {
  26121. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  26122. }
  26123. }
  26124. }
  26125. };
  26126. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26127. if (!this._texture) {
  26128. return;
  26129. }
  26130. var scene = this.getScene();
  26131. if (!scene) {
  26132. return;
  26133. }
  26134. this._samplingMode = samplingMode;
  26135. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26136. };
  26137. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26138. x *= this.uScale;
  26139. y *= this.vScale;
  26140. x -= 0.5 * this.uScale;
  26141. y -= 0.5 * this.vScale;
  26142. z -= 0.5;
  26143. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26144. t.x += 0.5 * this.uScale + this.uOffset;
  26145. t.y += 0.5 * this.vScale + this.vOffset;
  26146. t.z += 0.5;
  26147. };
  26148. Texture.prototype.getTextureMatrix = function () {
  26149. var _this = this;
  26150. if (this.uOffset === this._cachedUOffset &&
  26151. this.vOffset === this._cachedVOffset &&
  26152. this.uScale === this._cachedUScale &&
  26153. this.vScale === this._cachedVScale &&
  26154. this.uAng === this._cachedUAng &&
  26155. this.vAng === this._cachedVAng &&
  26156. this.wAng === this._cachedWAng) {
  26157. return this._cachedTextureMatrix;
  26158. }
  26159. this._cachedUOffset = this.uOffset;
  26160. this._cachedVOffset = this.vOffset;
  26161. this._cachedUScale = this.uScale;
  26162. this._cachedVScale = this.vScale;
  26163. this._cachedUAng = this.uAng;
  26164. this._cachedVAng = this.vAng;
  26165. this._cachedWAng = this.wAng;
  26166. if (!this._cachedTextureMatrix) {
  26167. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26168. this._rowGenerationMatrix = new BABYLON.Matrix();
  26169. this._t0 = BABYLON.Vector3.Zero();
  26170. this._t1 = BABYLON.Vector3.Zero();
  26171. this._t2 = BABYLON.Vector3.Zero();
  26172. }
  26173. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26174. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26175. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26176. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26177. this._t1.subtractInPlace(this._t0);
  26178. this._t2.subtractInPlace(this._t0);
  26179. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26180. this._cachedTextureMatrix.m[0] = this._t1.x;
  26181. this._cachedTextureMatrix.m[1] = this._t1.y;
  26182. this._cachedTextureMatrix.m[2] = this._t1.z;
  26183. this._cachedTextureMatrix.m[4] = this._t2.x;
  26184. this._cachedTextureMatrix.m[5] = this._t2.y;
  26185. this._cachedTextureMatrix.m[6] = this._t2.z;
  26186. this._cachedTextureMatrix.m[8] = this._t0.x;
  26187. this._cachedTextureMatrix.m[9] = this._t0.y;
  26188. this._cachedTextureMatrix.m[10] = this._t0.z;
  26189. var scene = this.getScene();
  26190. if (!scene) {
  26191. return this._cachedTextureMatrix;
  26192. }
  26193. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26194. return mat.hasTexture(_this);
  26195. });
  26196. return this._cachedTextureMatrix;
  26197. };
  26198. Texture.prototype.getReflectionTextureMatrix = function () {
  26199. var _this = this;
  26200. var scene = this.getScene();
  26201. if (!scene) {
  26202. return this._cachedTextureMatrix;
  26203. }
  26204. if (this.uOffset === this._cachedUOffset &&
  26205. this.vOffset === this._cachedVOffset &&
  26206. this.uScale === this._cachedUScale &&
  26207. this.vScale === this._cachedVScale &&
  26208. this.coordinatesMode === this._cachedCoordinatesMode) {
  26209. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  26210. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  26211. return this._cachedTextureMatrix;
  26212. }
  26213. }
  26214. else {
  26215. return this._cachedTextureMatrix;
  26216. }
  26217. }
  26218. if (!this._cachedTextureMatrix) {
  26219. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26220. }
  26221. if (!this._projectionModeMatrix) {
  26222. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  26223. }
  26224. this._cachedUOffset = this.uOffset;
  26225. this._cachedVOffset = this.vOffset;
  26226. this._cachedUScale = this.uScale;
  26227. this._cachedVScale = this.vScale;
  26228. this._cachedCoordinatesMode = this.coordinatesMode;
  26229. switch (this.coordinatesMode) {
  26230. case Texture.PLANAR_MODE:
  26231. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26232. this._cachedTextureMatrix[0] = this.uScale;
  26233. this._cachedTextureMatrix[5] = this.vScale;
  26234. this._cachedTextureMatrix[12] = this.uOffset;
  26235. this._cachedTextureMatrix[13] = this.vOffset;
  26236. break;
  26237. case Texture.PROJECTION_MODE:
  26238. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  26239. this._projectionModeMatrix.m[0] = 0.5;
  26240. this._projectionModeMatrix.m[5] = -0.5;
  26241. this._projectionModeMatrix.m[10] = 0.0;
  26242. this._projectionModeMatrix.m[12] = 0.5;
  26243. this._projectionModeMatrix.m[13] = 0.5;
  26244. this._projectionModeMatrix.m[14] = 1.0;
  26245. this._projectionModeMatrix.m[15] = 1.0;
  26246. var projectionMatrix = scene.getProjectionMatrix();
  26247. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  26248. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  26249. break;
  26250. default:
  26251. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26252. break;
  26253. }
  26254. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26255. return (mat.getActiveTextures().indexOf(_this) !== -1);
  26256. });
  26257. return this._cachedTextureMatrix;
  26258. };
  26259. Texture.prototype.clone = function () {
  26260. var _this = this;
  26261. return BABYLON.SerializationHelper.Clone(function () {
  26262. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  26263. }, this);
  26264. };
  26265. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  26266. get: function () {
  26267. if (!this._onLoadObservable) {
  26268. this._onLoadObservable = new BABYLON.Observable();
  26269. }
  26270. return this._onLoadObservable;
  26271. },
  26272. enumerable: true,
  26273. configurable: true
  26274. });
  26275. Texture.prototype.serialize = function () {
  26276. var serializationObject = _super.prototype.serialize.call(this);
  26277. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  26278. serializationObject.base64String = this._buffer;
  26279. serializationObject.name = serializationObject.name.replace("data:", "");
  26280. }
  26281. return serializationObject;
  26282. };
  26283. Texture.prototype.getClassName = function () {
  26284. return "Texture";
  26285. };
  26286. Texture.prototype.dispose = function () {
  26287. _super.prototype.dispose.call(this);
  26288. if (this.onLoadObservable) {
  26289. this.onLoadObservable.clear();
  26290. this._onLoadObservable = null;
  26291. }
  26292. this._delayedOnLoad = null;
  26293. this._delayedOnError = null;
  26294. };
  26295. // Statics
  26296. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26297. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26298. if (onLoad === void 0) { onLoad = null; }
  26299. if (onError === void 0) { onError = null; }
  26300. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26301. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  26302. };
  26303. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  26304. if (parsedTexture.customType) {
  26305. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  26306. // Update Sampling Mode
  26307. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  26308. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  26309. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  26310. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  26311. }
  26312. }
  26313. return parsedCustomTexture;
  26314. }
  26315. if (parsedTexture.isCube) {
  26316. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  26317. }
  26318. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  26319. return null;
  26320. }
  26321. var texture = BABYLON.SerializationHelper.Parse(function () {
  26322. var generateMipMaps = true;
  26323. if (parsedTexture.noMipmap) {
  26324. generateMipMaps = false;
  26325. }
  26326. if (parsedTexture.mirrorPlane) {
  26327. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26328. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  26329. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  26330. return mirrorTexture;
  26331. }
  26332. else if (parsedTexture.isRenderTarget) {
  26333. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26334. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  26335. return renderTargetTexture;
  26336. }
  26337. else {
  26338. var texture;
  26339. if (parsedTexture.base64String) {
  26340. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  26341. }
  26342. else {
  26343. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  26344. }
  26345. return texture;
  26346. }
  26347. }, parsedTexture, scene);
  26348. // Update Sampling Mode
  26349. if (parsedTexture.samplingMode) {
  26350. var sampling = parsedTexture.samplingMode;
  26351. if (texture._samplingMode !== sampling) {
  26352. texture.updateSamplingMode(sampling);
  26353. }
  26354. }
  26355. // Animations
  26356. if (parsedTexture.animations) {
  26357. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  26358. var parsedAnimation = parsedTexture.animations[animationIndex];
  26359. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26360. }
  26361. }
  26362. return texture;
  26363. };
  26364. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26365. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26366. if (noMipmap === void 0) { noMipmap = false; }
  26367. if (invertY === void 0) { invertY = true; }
  26368. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26369. if (onLoad === void 0) { onLoad = null; }
  26370. if (onError === void 0) { onError = null; }
  26371. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26372. if (name.substr(0, 5) !== "data:") {
  26373. name = "data:" + name;
  26374. }
  26375. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  26376. };
  26377. // Constants
  26378. Texture.NEAREST_SAMPLINGMODE = 1;
  26379. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  26380. Texture.BILINEAR_SAMPLINGMODE = 2;
  26381. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  26382. Texture.TRILINEAR_SAMPLINGMODE = 3;
  26383. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  26384. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  26385. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  26386. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  26387. Texture.NEAREST_LINEAR = 7;
  26388. Texture.NEAREST_NEAREST = 8;
  26389. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  26390. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  26391. Texture.LINEAR_LINEAR = 11;
  26392. Texture.LINEAR_NEAREST = 12;
  26393. Texture.EXPLICIT_MODE = 0;
  26394. Texture.SPHERICAL_MODE = 1;
  26395. Texture.PLANAR_MODE = 2;
  26396. Texture.CUBIC_MODE = 3;
  26397. Texture.PROJECTION_MODE = 4;
  26398. Texture.SKYBOX_MODE = 5;
  26399. Texture.INVCUBIC_MODE = 6;
  26400. Texture.EQUIRECTANGULAR_MODE = 7;
  26401. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  26402. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  26403. Texture.CLAMP_ADDRESSMODE = 0;
  26404. Texture.WRAP_ADDRESSMODE = 1;
  26405. Texture.MIRROR_ADDRESSMODE = 2;
  26406. __decorate([
  26407. BABYLON.serialize()
  26408. ], Texture.prototype, "url", void 0);
  26409. __decorate([
  26410. BABYLON.serialize()
  26411. ], Texture.prototype, "uOffset", void 0);
  26412. __decorate([
  26413. BABYLON.serialize()
  26414. ], Texture.prototype, "vOffset", void 0);
  26415. __decorate([
  26416. BABYLON.serialize()
  26417. ], Texture.prototype, "uScale", void 0);
  26418. __decorate([
  26419. BABYLON.serialize()
  26420. ], Texture.prototype, "vScale", void 0);
  26421. __decorate([
  26422. BABYLON.serialize()
  26423. ], Texture.prototype, "uAng", void 0);
  26424. __decorate([
  26425. BABYLON.serialize()
  26426. ], Texture.prototype, "vAng", void 0);
  26427. __decorate([
  26428. BABYLON.serialize()
  26429. ], Texture.prototype, "wAng", void 0);
  26430. __decorate([
  26431. BABYLON.serialize()
  26432. ], Texture.prototype, "isBlocking", null);
  26433. return Texture;
  26434. }(BABYLON.BaseTexture));
  26435. BABYLON.Texture = Texture;
  26436. })(BABYLON || (BABYLON = {}));
  26437. //# sourceMappingURL=babylon.texture.js.map
  26438. var BABYLON;
  26439. (function (BABYLON) {
  26440. var _InstancesBatch = /** @class */ (function () {
  26441. function _InstancesBatch() {
  26442. this.mustReturn = false;
  26443. this.visibleInstances = new Array();
  26444. this.renderSelf = new Array();
  26445. }
  26446. return _InstancesBatch;
  26447. }());
  26448. BABYLON._InstancesBatch = _InstancesBatch;
  26449. var Mesh = /** @class */ (function (_super) {
  26450. __extends(Mesh, _super);
  26451. /**
  26452. * @constructor
  26453. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  26454. * @param {Scene} scene The scene to add this mesh to.
  26455. * @param {Node} parent The parent of this mesh, if it has one
  26456. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  26457. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  26458. * When false, achieved by calling a clone(), also passing False.
  26459. * This will make creation of children, recursive.
  26460. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  26461. */
  26462. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  26463. if (scene === void 0) { scene = null; }
  26464. if (parent === void 0) { parent = null; }
  26465. if (source === void 0) { source = null; }
  26466. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  26467. var _this = _super.call(this, name, scene) || this;
  26468. // Events
  26469. /**
  26470. * An event triggered before rendering the mesh
  26471. * @type {BABYLON.Observable}
  26472. */
  26473. _this.onBeforeRenderObservable = new BABYLON.Observable();
  26474. /**
  26475. * An event triggered after rendering the mesh
  26476. * @type {BABYLON.Observable}
  26477. */
  26478. _this.onAfterRenderObservable = new BABYLON.Observable();
  26479. /**
  26480. * An event triggered before drawing the mesh
  26481. * @type {BABYLON.Observable}
  26482. */
  26483. _this.onBeforeDrawObservable = new BABYLON.Observable();
  26484. // Members
  26485. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26486. _this.instances = new Array();
  26487. _this._LODLevels = new Array();
  26488. _this._visibleInstances = {};
  26489. _this._renderIdForInstances = new Array();
  26490. _this._batchCache = new _InstancesBatch();
  26491. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  26492. // Use by builder only to know what orientation were the mesh build in.
  26493. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  26494. _this.overrideMaterialSideOrientation = null;
  26495. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  26496. // Will be used to save a source mesh reference, If any
  26497. _this._source = null;
  26498. scene = _this.getScene();
  26499. if (source) {
  26500. // Source mesh
  26501. _this._source = source;
  26502. // Geometry
  26503. if (source._geometry) {
  26504. source._geometry.applyToMesh(_this);
  26505. }
  26506. // Deep copy
  26507. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  26508. // Metadata
  26509. if (source.metadata && source.metadata.clone) {
  26510. _this.metadata = source.metadata.clone();
  26511. }
  26512. else {
  26513. _this.metadata = source.metadata;
  26514. }
  26515. // Tags
  26516. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  26517. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  26518. }
  26519. // Parent
  26520. _this.parent = source.parent;
  26521. // Pivot
  26522. _this.setPivotMatrix(source.getPivotMatrix());
  26523. _this.id = name + "." + source.id;
  26524. // Material
  26525. _this.material = source.material;
  26526. var index;
  26527. if (!doNotCloneChildren) {
  26528. // Children
  26529. var directDescendants = source.getDescendants(true);
  26530. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  26531. var child = directDescendants[index_1];
  26532. if (child.clone) {
  26533. child.clone(name + "." + child.name, _this);
  26534. }
  26535. }
  26536. }
  26537. // Physics clone
  26538. var physicsEngine = _this.getScene().getPhysicsEngine();
  26539. if (clonePhysicsImpostor && physicsEngine) {
  26540. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  26541. if (impostor) {
  26542. _this.physicsImpostor = impostor.clone(_this);
  26543. }
  26544. }
  26545. // Particles
  26546. for (index = 0; index < scene.particleSystems.length; index++) {
  26547. var system = scene.particleSystems[index];
  26548. if (system.emitter === source) {
  26549. system.clone(system.name, _this);
  26550. }
  26551. }
  26552. _this.computeWorldMatrix(true);
  26553. }
  26554. // Parent
  26555. if (parent !== null) {
  26556. _this.parent = parent;
  26557. }
  26558. return _this;
  26559. }
  26560. Object.defineProperty(Mesh, "FRONTSIDE", {
  26561. /**
  26562. * Mesh side orientation : usually the external or front surface
  26563. */
  26564. get: function () {
  26565. return Mesh._FRONTSIDE;
  26566. },
  26567. enumerable: true,
  26568. configurable: true
  26569. });
  26570. Object.defineProperty(Mesh, "BACKSIDE", {
  26571. /**
  26572. * Mesh side orientation : usually the internal or back surface
  26573. */
  26574. get: function () {
  26575. return Mesh._BACKSIDE;
  26576. },
  26577. enumerable: true,
  26578. configurable: true
  26579. });
  26580. Object.defineProperty(Mesh, "DOUBLESIDE", {
  26581. /**
  26582. * Mesh side orientation : both internal and external or front and back surfaces
  26583. */
  26584. get: function () {
  26585. return Mesh._DOUBLESIDE;
  26586. },
  26587. enumerable: true,
  26588. configurable: true
  26589. });
  26590. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  26591. /**
  26592. * Mesh side orientation : by default, `FRONTSIDE`
  26593. */
  26594. get: function () {
  26595. return Mesh._DEFAULTSIDE;
  26596. },
  26597. enumerable: true,
  26598. configurable: true
  26599. });
  26600. Object.defineProperty(Mesh, "NO_CAP", {
  26601. /**
  26602. * Mesh cap setting : no cap
  26603. */
  26604. get: function () {
  26605. return Mesh._NO_CAP;
  26606. },
  26607. enumerable: true,
  26608. configurable: true
  26609. });
  26610. Object.defineProperty(Mesh, "CAP_START", {
  26611. /**
  26612. * Mesh cap setting : one cap at the beginning of the mesh
  26613. */
  26614. get: function () {
  26615. return Mesh._CAP_START;
  26616. },
  26617. enumerable: true,
  26618. configurable: true
  26619. });
  26620. Object.defineProperty(Mesh, "CAP_END", {
  26621. /**
  26622. * Mesh cap setting : one cap at the end of the mesh
  26623. */
  26624. get: function () {
  26625. return Mesh._CAP_END;
  26626. },
  26627. enumerable: true,
  26628. configurable: true
  26629. });
  26630. Object.defineProperty(Mesh, "CAP_ALL", {
  26631. /**
  26632. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  26633. */
  26634. get: function () {
  26635. return Mesh._CAP_ALL;
  26636. },
  26637. enumerable: true,
  26638. configurable: true
  26639. });
  26640. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  26641. set: function (callback) {
  26642. if (this._onBeforeDrawObserver) {
  26643. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  26644. }
  26645. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  26646. },
  26647. enumerable: true,
  26648. configurable: true
  26649. });
  26650. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  26651. get: function () {
  26652. return this._morphTargetManager;
  26653. },
  26654. set: function (value) {
  26655. if (this._morphTargetManager === value) {
  26656. return;
  26657. }
  26658. this._morphTargetManager = value;
  26659. this._syncGeometryWithMorphTargetManager();
  26660. },
  26661. enumerable: true,
  26662. configurable: true
  26663. });
  26664. Object.defineProperty(Mesh.prototype, "source", {
  26665. get: function () {
  26666. return this._source;
  26667. },
  26668. enumerable: true,
  26669. configurable: true
  26670. });
  26671. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  26672. get: function () {
  26673. return this._unIndexed;
  26674. },
  26675. set: function (value) {
  26676. if (this._unIndexed !== value) {
  26677. this._unIndexed = value;
  26678. this._markSubMeshesAsAttributesDirty();
  26679. }
  26680. },
  26681. enumerable: true,
  26682. configurable: true
  26683. });
  26684. // Methods
  26685. /**
  26686. * Returns the string "Mesh".
  26687. */
  26688. Mesh.prototype.getClassName = function () {
  26689. return "Mesh";
  26690. };
  26691. /**
  26692. * Returns a string.
  26693. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26694. */
  26695. Mesh.prototype.toString = function (fullDetails) {
  26696. var ret = _super.prototype.toString.call(this, fullDetails);
  26697. ret += ", n vertices: " + this.getTotalVertices();
  26698. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  26699. if (this.animations) {
  26700. for (var i = 0; i < this.animations.length; i++) {
  26701. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  26702. }
  26703. }
  26704. if (fullDetails) {
  26705. if (this._geometry) {
  26706. var ib = this.getIndices();
  26707. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26708. if (vb && ib) {
  26709. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  26710. }
  26711. }
  26712. else {
  26713. ret += ", flat shading: UNKNOWN";
  26714. }
  26715. }
  26716. return ret;
  26717. };
  26718. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  26719. /**
  26720. * True if the mesh has some Levels Of Details (LOD).
  26721. * Returns a boolean.
  26722. */
  26723. get: function () {
  26724. return this._LODLevels.length > 0;
  26725. },
  26726. enumerable: true,
  26727. configurable: true
  26728. });
  26729. /**
  26730. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  26731. * @returns an array of {BABYLON.MeshLODLevel}
  26732. */
  26733. Mesh.prototype.getLODLevels = function () {
  26734. return this._LODLevels;
  26735. };
  26736. Mesh.prototype._sortLODLevels = function () {
  26737. this._LODLevels.sort(function (a, b) {
  26738. if (a.distance < b.distance) {
  26739. return 1;
  26740. }
  26741. if (a.distance > b.distance) {
  26742. return -1;
  26743. }
  26744. return 0;
  26745. });
  26746. };
  26747. /**
  26748. * Add a mesh as LOD level triggered at the given distance.
  26749. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26750. * @param {number} distance The distance from the center of the object to show this level
  26751. * @param {Mesh} mesh The mesh to be added as LOD level
  26752. * @return {Mesh} This mesh (for chaining)
  26753. */
  26754. Mesh.prototype.addLODLevel = function (distance, mesh) {
  26755. if (mesh && mesh._masterMesh) {
  26756. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  26757. return this;
  26758. }
  26759. var level = new BABYLON.MeshLODLevel(distance, mesh);
  26760. this._LODLevels.push(level);
  26761. if (mesh) {
  26762. mesh._masterMesh = this;
  26763. }
  26764. this._sortLODLevels();
  26765. return this;
  26766. };
  26767. /**
  26768. * Returns the LOD level mesh at the passed distance or null if not found.
  26769. * It is related to the method `addLODLevel(distance, mesh)`.
  26770. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26771. * Returns an object Mesh or `null`.
  26772. */
  26773. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  26774. for (var index = 0; index < this._LODLevels.length; index++) {
  26775. var level = this._LODLevels[index];
  26776. if (level.distance === distance) {
  26777. return level.mesh;
  26778. }
  26779. }
  26780. return null;
  26781. };
  26782. /**
  26783. * Remove a mesh from the LOD array
  26784. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26785. * @param {Mesh} mesh The mesh to be removed.
  26786. * @return {Mesh} This mesh (for chaining)
  26787. */
  26788. Mesh.prototype.removeLODLevel = function (mesh) {
  26789. for (var index = 0; index < this._LODLevels.length; index++) {
  26790. if (this._LODLevels[index].mesh === mesh) {
  26791. this._LODLevels.splice(index, 1);
  26792. if (mesh) {
  26793. mesh._masterMesh = null;
  26794. }
  26795. }
  26796. }
  26797. this._sortLODLevels();
  26798. return this;
  26799. };
  26800. /**
  26801. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  26802. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26803. */
  26804. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  26805. if (!this._LODLevels || this._LODLevels.length === 0) {
  26806. return this;
  26807. }
  26808. var bSphere;
  26809. if (boundingSphere) {
  26810. bSphere = boundingSphere;
  26811. }
  26812. else {
  26813. var boundingInfo = this.getBoundingInfo();
  26814. bSphere = boundingInfo.boundingSphere;
  26815. }
  26816. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  26817. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  26818. if (this.onLODLevelSelection) {
  26819. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  26820. }
  26821. return this;
  26822. }
  26823. for (var index = 0; index < this._LODLevels.length; index++) {
  26824. var level = this._LODLevels[index];
  26825. if (level.distance < distanceToCamera) {
  26826. if (level.mesh) {
  26827. level.mesh._preActivate();
  26828. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  26829. }
  26830. if (this.onLODLevelSelection) {
  26831. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  26832. }
  26833. return level.mesh;
  26834. }
  26835. }
  26836. if (this.onLODLevelSelection) {
  26837. this.onLODLevelSelection(distanceToCamera, this, this);
  26838. }
  26839. return this;
  26840. };
  26841. Object.defineProperty(Mesh.prototype, "geometry", {
  26842. /**
  26843. * Returns the mesh internal Geometry object.
  26844. */
  26845. get: function () {
  26846. return this._geometry;
  26847. },
  26848. enumerable: true,
  26849. configurable: true
  26850. });
  26851. /**
  26852. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  26853. */
  26854. Mesh.prototype.getTotalVertices = function () {
  26855. if (this._geometry === null || this._geometry === undefined) {
  26856. return 0;
  26857. }
  26858. return this._geometry.getTotalVertices();
  26859. };
  26860. /**
  26861. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  26862. * 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.
  26863. * You can force the copy with forceCopy === true
  26864. * Returns null if the mesh has no geometry or no vertex buffer.
  26865. * Possible `kind` values :
  26866. * - BABYLON.VertexBuffer.PositionKind
  26867. * - BABYLON.VertexBuffer.UVKind
  26868. * - BABYLON.VertexBuffer.UV2Kind
  26869. * - BABYLON.VertexBuffer.UV3Kind
  26870. * - BABYLON.VertexBuffer.UV4Kind
  26871. * - BABYLON.VertexBuffer.UV5Kind
  26872. * - BABYLON.VertexBuffer.UV6Kind
  26873. * - BABYLON.VertexBuffer.ColorKind
  26874. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26875. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26876. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26877. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26878. */
  26879. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  26880. if (!this._geometry) {
  26881. return null;
  26882. }
  26883. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  26884. };
  26885. /**
  26886. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  26887. * Returns `null` if the mesh has no geometry.
  26888. * Possible `kind` values :
  26889. * - BABYLON.VertexBuffer.PositionKind
  26890. * - BABYLON.VertexBuffer.UVKind
  26891. * - BABYLON.VertexBuffer.UV2Kind
  26892. * - BABYLON.VertexBuffer.UV3Kind
  26893. * - BABYLON.VertexBuffer.UV4Kind
  26894. * - BABYLON.VertexBuffer.UV5Kind
  26895. * - BABYLON.VertexBuffer.UV6Kind
  26896. * - BABYLON.VertexBuffer.ColorKind
  26897. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26898. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26899. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26900. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26901. */
  26902. Mesh.prototype.getVertexBuffer = function (kind) {
  26903. if (!this._geometry) {
  26904. return null;
  26905. }
  26906. return this._geometry.getVertexBuffer(kind);
  26907. };
  26908. /**
  26909. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  26910. * Possible `kind` values :
  26911. * - BABYLON.VertexBuffer.PositionKind
  26912. * - BABYLON.VertexBuffer.UVKind
  26913. * - BABYLON.VertexBuffer.UV2Kind
  26914. * - BABYLON.VertexBuffer.UV3Kind
  26915. * - BABYLON.VertexBuffer.UV4Kind
  26916. * - BABYLON.VertexBuffer.UV5Kind
  26917. * - BABYLON.VertexBuffer.UV6Kind
  26918. * - BABYLON.VertexBuffer.ColorKind
  26919. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26920. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26921. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26922. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26923. */
  26924. Mesh.prototype.isVerticesDataPresent = function (kind) {
  26925. if (!this._geometry) {
  26926. if (this._delayInfo) {
  26927. return this._delayInfo.indexOf(kind) !== -1;
  26928. }
  26929. return false;
  26930. }
  26931. return this._geometry.isVerticesDataPresent(kind);
  26932. };
  26933. /**
  26934. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  26935. * Possible `kind` values :
  26936. * - BABYLON.VertexBuffer.PositionKind
  26937. * - BABYLON.VertexBuffer.UVKind
  26938. * - BABYLON.VertexBuffer.UV2Kind
  26939. * - BABYLON.VertexBuffer.UV3Kind
  26940. * - BABYLON.VertexBuffer.UV4Kind
  26941. * - BABYLON.VertexBuffer.UV5Kind
  26942. * - BABYLON.VertexBuffer.UV6Kind
  26943. * - BABYLON.VertexBuffer.ColorKind
  26944. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26945. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26946. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26947. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26948. */
  26949. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  26950. if (!this._geometry) {
  26951. if (this._delayInfo) {
  26952. return this._delayInfo.indexOf(kind) !== -1;
  26953. }
  26954. return false;
  26955. }
  26956. return this._geometry.isVertexBufferUpdatable(kind);
  26957. };
  26958. /**
  26959. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  26960. * Possible `kind` values :
  26961. * - BABYLON.VertexBuffer.PositionKind
  26962. * - BABYLON.VertexBuffer.UVKind
  26963. * - BABYLON.VertexBuffer.UV2Kind
  26964. * - BABYLON.VertexBuffer.UV3Kind
  26965. * - BABYLON.VertexBuffer.UV4Kind
  26966. * - BABYLON.VertexBuffer.UV5Kind
  26967. * - BABYLON.VertexBuffer.UV6Kind
  26968. * - BABYLON.VertexBuffer.ColorKind
  26969. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26970. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26971. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26972. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26973. */
  26974. Mesh.prototype.getVerticesDataKinds = function () {
  26975. if (!this._geometry) {
  26976. var result = new Array();
  26977. if (this._delayInfo) {
  26978. this._delayInfo.forEach(function (kind, index, array) {
  26979. result.push(kind);
  26980. });
  26981. }
  26982. return result;
  26983. }
  26984. return this._geometry.getVerticesDataKinds();
  26985. };
  26986. /**
  26987. * Returns a positive integer : the total number of indices in this mesh geometry.
  26988. * Returns zero if the mesh has no geometry.
  26989. */
  26990. Mesh.prototype.getTotalIndices = function () {
  26991. if (!this._geometry) {
  26992. return 0;
  26993. }
  26994. return this._geometry.getTotalIndices();
  26995. };
  26996. /**
  26997. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  26998. * 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.
  26999. * Returns an empty array if the mesh has no geometry.
  27000. */
  27001. Mesh.prototype.getIndices = function (copyWhenShared) {
  27002. if (!this._geometry) {
  27003. return [];
  27004. }
  27005. return this._geometry.getIndices(copyWhenShared);
  27006. };
  27007. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27008. get: function () {
  27009. return this._masterMesh !== null && this._masterMesh !== undefined;
  27010. },
  27011. enumerable: true,
  27012. configurable: true
  27013. });
  27014. /**
  27015. * Determine if the current mesh is ready to be rendered
  27016. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27017. * @returns true if all associated assets are ready (material, textures, shaders)
  27018. */
  27019. Mesh.prototype.isReady = function (forceInstanceSupport) {
  27020. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27021. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27022. return false;
  27023. }
  27024. if (!_super.prototype.isReady.call(this)) {
  27025. return false;
  27026. }
  27027. if (!this.subMeshes || this.subMeshes.length === 0) {
  27028. return true;
  27029. }
  27030. var engine = this.getEngine();
  27031. var scene = this.getScene();
  27032. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27033. this.computeWorldMatrix();
  27034. var mat = this.material || scene.defaultMaterial;
  27035. if (mat) {
  27036. if (mat.storeEffectOnSubMeshes) {
  27037. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27038. var subMesh = _a[_i];
  27039. var effectiveMaterial = subMesh.getMaterial();
  27040. if (effectiveMaterial) {
  27041. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27042. return false;
  27043. }
  27044. }
  27045. }
  27046. }
  27047. else {
  27048. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27049. return false;
  27050. }
  27051. }
  27052. }
  27053. // Shadows
  27054. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27055. var light = _c[_b];
  27056. var generator = light.getShadowGenerator();
  27057. if (generator) {
  27058. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27059. var subMesh = _e[_d];
  27060. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27061. return false;
  27062. }
  27063. }
  27064. }
  27065. }
  27066. // LOD
  27067. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27068. var lod = _g[_f];
  27069. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27070. return false;
  27071. }
  27072. }
  27073. return true;
  27074. };
  27075. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27076. /**
  27077. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27078. * This property is pertinent only for updatable parametric shapes.
  27079. */
  27080. get: function () {
  27081. return this._areNormalsFrozen;
  27082. },
  27083. enumerable: true,
  27084. configurable: true
  27085. });
  27086. /**
  27087. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27088. * It has no effect at all on other shapes.
  27089. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27090. * Returns the Mesh.
  27091. */
  27092. Mesh.prototype.freezeNormals = function () {
  27093. this._areNormalsFrozen = true;
  27094. return this;
  27095. };
  27096. /**
  27097. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27098. * It has no effect at all on other shapes.
  27099. * It reactivates the mesh normals computation if it was previously frozen.
  27100. * Returns the Mesh.
  27101. */
  27102. Mesh.prototype.unfreezeNormals = function () {
  27103. this._areNormalsFrozen = false;
  27104. return this;
  27105. };
  27106. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  27107. /**
  27108. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  27109. */
  27110. set: function (count) {
  27111. this._overridenInstanceCount = count;
  27112. },
  27113. enumerable: true,
  27114. configurable: true
  27115. });
  27116. // Methods
  27117. Mesh.prototype._preActivate = function () {
  27118. var sceneRenderId = this.getScene().getRenderId();
  27119. if (this._preActivateId === sceneRenderId) {
  27120. return this;
  27121. }
  27122. this._preActivateId = sceneRenderId;
  27123. this._visibleInstances = null;
  27124. return this;
  27125. };
  27126. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  27127. if (this._visibleInstances) {
  27128. this._visibleInstances.intermediateDefaultRenderId = renderId;
  27129. }
  27130. return this;
  27131. };
  27132. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  27133. if (!this._visibleInstances) {
  27134. this._visibleInstances = {};
  27135. this._visibleInstances.defaultRenderId = renderId;
  27136. this._visibleInstances.selfDefaultRenderId = this._renderId;
  27137. }
  27138. if (!this._visibleInstances[renderId]) {
  27139. this._visibleInstances[renderId] = new Array();
  27140. }
  27141. this._visibleInstances[renderId].push(instance);
  27142. return this;
  27143. };
  27144. /**
  27145. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  27146. * This means the mesh underlying bounding box and sphere are recomputed.
  27147. * Returns the Mesh.
  27148. */
  27149. Mesh.prototype.refreshBoundingInfo = function () {
  27150. return this._refreshBoundingInfo(false);
  27151. };
  27152. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  27153. if (this._boundingInfo && this._boundingInfo.isLocked) {
  27154. return this;
  27155. }
  27156. var data = this._getPositionData(applySkeleton);
  27157. if (data) {
  27158. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  27159. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27160. }
  27161. if (this.subMeshes) {
  27162. for (var index = 0; index < this.subMeshes.length; index++) {
  27163. this.subMeshes[index].refreshBoundingInfo();
  27164. }
  27165. }
  27166. this._updateBoundingInfo();
  27167. return this;
  27168. };
  27169. Mesh.prototype._getPositionData = function (applySkeleton) {
  27170. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27171. if (data && applySkeleton && this.skeleton) {
  27172. data = BABYLON.Tools.Slice(data);
  27173. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27174. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27175. if (matricesWeightsData && matricesIndicesData) {
  27176. var needExtras = this.numBoneInfluencers > 4;
  27177. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27178. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27179. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  27180. var tempVector = BABYLON.Tmp.Vector3[0];
  27181. var finalMatrix = BABYLON.Tmp.Matrix[0];
  27182. var tempMatrix = BABYLON.Tmp.Matrix[1];
  27183. var matWeightIdx = 0;
  27184. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  27185. finalMatrix.reset();
  27186. var inf;
  27187. var weight;
  27188. for (inf = 0; inf < 4; inf++) {
  27189. weight = matricesWeightsData[matWeightIdx + inf];
  27190. if (weight <= 0)
  27191. break;
  27192. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27193. finalMatrix.addToSelf(tempMatrix);
  27194. }
  27195. if (needExtras) {
  27196. for (inf = 0; inf < 4; inf++) {
  27197. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27198. if (weight <= 0)
  27199. break;
  27200. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27201. finalMatrix.addToSelf(tempMatrix);
  27202. }
  27203. }
  27204. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  27205. tempVector.toArray(data, index);
  27206. }
  27207. }
  27208. }
  27209. return data;
  27210. };
  27211. Mesh.prototype._createGlobalSubMesh = function (force) {
  27212. var totalVertices = this.getTotalVertices();
  27213. if (!totalVertices || !this.getIndices()) {
  27214. return null;
  27215. }
  27216. // Check if we need to recreate the submeshes
  27217. if (this.subMeshes && this.subMeshes.length > 0) {
  27218. var ib = this.getIndices();
  27219. if (!ib) {
  27220. return null;
  27221. }
  27222. var totalIndices = ib.length;
  27223. var needToRecreate = false;
  27224. if (force) {
  27225. needToRecreate = true;
  27226. }
  27227. else {
  27228. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27229. var submesh = _a[_i];
  27230. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  27231. needToRecreate = true;
  27232. break;
  27233. }
  27234. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  27235. needToRecreate = true;
  27236. break;
  27237. }
  27238. }
  27239. }
  27240. if (!needToRecreate) {
  27241. return this.subMeshes[0];
  27242. }
  27243. }
  27244. this.releaseSubMeshes();
  27245. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  27246. };
  27247. Mesh.prototype.subdivide = function (count) {
  27248. if (count < 1) {
  27249. return;
  27250. }
  27251. var totalIndices = this.getTotalIndices();
  27252. var subdivisionSize = (totalIndices / count) | 0;
  27253. var offset = 0;
  27254. // Ensure that subdivisionSize is a multiple of 3
  27255. while (subdivisionSize % 3 !== 0) {
  27256. subdivisionSize++;
  27257. }
  27258. this.releaseSubMeshes();
  27259. for (var index = 0; index < count; index++) {
  27260. if (offset >= totalIndices) {
  27261. break;
  27262. }
  27263. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  27264. offset += subdivisionSize;
  27265. }
  27266. this.synchronizeInstances();
  27267. };
  27268. /**
  27269. * Sets the vertex data of the mesh geometry for the requested `kind`.
  27270. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  27271. * The `data` are either a numeric array either a Float32Array.
  27272. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  27273. * 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).
  27274. * Note that a new underlying VertexBuffer object is created each call.
  27275. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  27276. *
  27277. * Possible `kind` values :
  27278. * - BABYLON.VertexBuffer.PositionKind
  27279. * - BABYLON.VertexBuffer.UVKind
  27280. * - BABYLON.VertexBuffer.UV2Kind
  27281. * - BABYLON.VertexBuffer.UV3Kind
  27282. * - BABYLON.VertexBuffer.UV4Kind
  27283. * - BABYLON.VertexBuffer.UV5Kind
  27284. * - BABYLON.VertexBuffer.UV6Kind
  27285. * - BABYLON.VertexBuffer.ColorKind
  27286. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27287. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27288. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27289. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27290. *
  27291. * Returns the Mesh.
  27292. */
  27293. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27294. if (updatable === void 0) { updatable = false; }
  27295. if (!this._geometry) {
  27296. var vertexData = new BABYLON.VertexData();
  27297. vertexData.set(data, kind);
  27298. var scene = this.getScene();
  27299. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27300. }
  27301. else {
  27302. this._geometry.setVerticesData(kind, data, updatable, stride);
  27303. }
  27304. return this;
  27305. };
  27306. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  27307. if (updatable === void 0) { updatable = true; }
  27308. var vb = this.getVertexBuffer(kind);
  27309. if (!vb || vb.isUpdatable() === updatable) {
  27310. return;
  27311. }
  27312. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  27313. };
  27314. /**
  27315. * Sets the mesh VertexBuffer.
  27316. * Returns the Mesh.
  27317. */
  27318. Mesh.prototype.setVerticesBuffer = function (buffer) {
  27319. if (!this._geometry) {
  27320. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  27321. }
  27322. this._geometry.setVerticesBuffer(buffer);
  27323. return this;
  27324. };
  27325. /**
  27326. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  27327. * If the mesh has no geometry, it is simply returned as it is.
  27328. * The `data` are either a numeric array either a Float32Array.
  27329. * No new underlying VertexBuffer object is created.
  27330. * 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.
  27331. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  27332. *
  27333. * Possible `kind` values :
  27334. * - BABYLON.VertexBuffer.PositionKind
  27335. * - BABYLON.VertexBuffer.UVKind
  27336. * - BABYLON.VertexBuffer.UV2Kind
  27337. * - BABYLON.VertexBuffer.UV3Kind
  27338. * - BABYLON.VertexBuffer.UV4Kind
  27339. * - BABYLON.VertexBuffer.UV5Kind
  27340. * - BABYLON.VertexBuffer.UV6Kind
  27341. * - BABYLON.VertexBuffer.ColorKind
  27342. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27343. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27344. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27345. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27346. *
  27347. * Returns the Mesh.
  27348. */
  27349. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  27350. if (!this._geometry) {
  27351. return this;
  27352. }
  27353. if (!makeItUnique) {
  27354. this._geometry.updateVerticesData(kind, data, updateExtends);
  27355. }
  27356. else {
  27357. this.makeGeometryUnique();
  27358. this.updateVerticesData(kind, data, updateExtends, false);
  27359. }
  27360. return this;
  27361. };
  27362. /**
  27363. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  27364. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  27365. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  27366. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  27367. * Returns the Mesh.
  27368. */
  27369. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  27370. if (computeNormals === void 0) { computeNormals = true; }
  27371. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27372. if (!positions) {
  27373. return this;
  27374. }
  27375. positionFunction(positions);
  27376. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  27377. if (computeNormals) {
  27378. var indices = this.getIndices();
  27379. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27380. if (!normals) {
  27381. return this;
  27382. }
  27383. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  27384. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  27385. }
  27386. return this;
  27387. };
  27388. /**
  27389. * Creates a un-shared specific occurence of the geometry for the mesh.
  27390. * Returns the Mesh.
  27391. */
  27392. Mesh.prototype.makeGeometryUnique = function () {
  27393. if (!this._geometry) {
  27394. return this;
  27395. }
  27396. var oldGeometry = this._geometry;
  27397. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  27398. oldGeometry.releaseForMesh(this, true);
  27399. geometry.applyToMesh(this);
  27400. return this;
  27401. };
  27402. /**
  27403. * Sets the mesh indices.
  27404. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  27405. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  27406. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  27407. * This method creates a new index buffer each call.
  27408. * Returns the Mesh.
  27409. */
  27410. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  27411. if (totalVertices === void 0) { totalVertices = null; }
  27412. if (updatable === void 0) { updatable = false; }
  27413. if (!this._geometry) {
  27414. var vertexData = new BABYLON.VertexData();
  27415. vertexData.indices = indices;
  27416. var scene = this.getScene();
  27417. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27418. }
  27419. else {
  27420. this._geometry.setIndices(indices, totalVertices, updatable);
  27421. }
  27422. return this;
  27423. };
  27424. /**
  27425. * Update the current index buffer
  27426. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  27427. * Returns the Mesh.
  27428. */
  27429. Mesh.prototype.updateIndices = function (indices, offset) {
  27430. if (!this._geometry) {
  27431. return this;
  27432. }
  27433. this._geometry.updateIndices(indices, offset);
  27434. return this;
  27435. };
  27436. /**
  27437. * Invert the geometry to move from a right handed system to a left handed one.
  27438. * Returns the Mesh.
  27439. */
  27440. Mesh.prototype.toLeftHanded = function () {
  27441. if (!this._geometry) {
  27442. return this;
  27443. }
  27444. this._geometry.toLeftHanded();
  27445. return this;
  27446. };
  27447. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  27448. if (!this._geometry) {
  27449. return this;
  27450. }
  27451. var engine = this.getScene().getEngine();
  27452. // Wireframe
  27453. var indexToBind;
  27454. if (this._unIndexed) {
  27455. indexToBind = null;
  27456. }
  27457. else {
  27458. switch (fillMode) {
  27459. case BABYLON.Material.PointFillMode:
  27460. indexToBind = null;
  27461. break;
  27462. case BABYLON.Material.WireFrameFillMode:
  27463. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  27464. break;
  27465. default:
  27466. case BABYLON.Material.TriangleFillMode:
  27467. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  27468. break;
  27469. }
  27470. }
  27471. // VBOs
  27472. this._geometry._bind(effect, indexToBind);
  27473. return this;
  27474. };
  27475. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  27476. if (alternate === void 0) { alternate = false; }
  27477. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27478. return this;
  27479. }
  27480. this.onBeforeDrawObservable.notifyObservers(this);
  27481. var scene = this.getScene();
  27482. var engine = scene.getEngine();
  27483. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  27484. // or triangles as points
  27485. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  27486. }
  27487. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  27488. // Triangles as wireframe
  27489. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  27490. }
  27491. else {
  27492. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  27493. }
  27494. if (scene._isAlternateRenderingEnabled && !alternate) {
  27495. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  27496. if (!effect || !scene.activeCamera) {
  27497. return this;
  27498. }
  27499. scene._switchToAlternateCameraConfiguration(true);
  27500. this._effectiveMaterial.bindView(effect);
  27501. this._effectiveMaterial.bindViewProjection(effect);
  27502. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  27503. this._draw(subMesh, fillMode, instancesCount, true);
  27504. engine.setViewport(scene.activeCamera.viewport);
  27505. scene._switchToAlternateCameraConfiguration(false);
  27506. this._effectiveMaterial.bindView(effect);
  27507. this._effectiveMaterial.bindViewProjection(effect);
  27508. }
  27509. return this;
  27510. };
  27511. /**
  27512. * Registers for this mesh a javascript function called just before the rendering process.
  27513. * This function is passed the current mesh.
  27514. * Return the Mesh.
  27515. */
  27516. Mesh.prototype.registerBeforeRender = function (func) {
  27517. this.onBeforeRenderObservable.add(func);
  27518. return this;
  27519. };
  27520. /**
  27521. * Disposes a previously registered javascript function called before the rendering.
  27522. * This function is passed the current mesh.
  27523. * Returns the Mesh.
  27524. */
  27525. Mesh.prototype.unregisterBeforeRender = function (func) {
  27526. this.onBeforeRenderObservable.removeCallback(func);
  27527. return this;
  27528. };
  27529. /**
  27530. * Registers for this mesh a javascript function called just after the rendering is complete.
  27531. * This function is passed the current mesh.
  27532. * Returns the Mesh.
  27533. */
  27534. Mesh.prototype.registerAfterRender = function (func) {
  27535. this.onAfterRenderObservable.add(func);
  27536. return this;
  27537. };
  27538. /**
  27539. * Disposes a previously registered javascript function called after the rendering.
  27540. * This function is passed the current mesh.
  27541. * Return the Mesh.
  27542. */
  27543. Mesh.prototype.unregisterAfterRender = function (func) {
  27544. this.onAfterRenderObservable.removeCallback(func);
  27545. return this;
  27546. };
  27547. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  27548. var scene = this.getScene();
  27549. this._batchCache.mustReturn = false;
  27550. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  27551. this._batchCache.visibleInstances[subMeshId] = null;
  27552. if (this._visibleInstances) {
  27553. var currentRenderId = scene.getRenderId();
  27554. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  27555. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  27556. var selfRenderId = this._renderId;
  27557. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  27558. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  27559. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  27560. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  27561. }
  27562. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  27563. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  27564. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  27565. this._batchCache.mustReturn = true;
  27566. return this._batchCache;
  27567. }
  27568. if (currentRenderId !== selfRenderId) {
  27569. this._batchCache.renderSelf[subMeshId] = false;
  27570. }
  27571. }
  27572. this._renderIdForInstances[subMeshId] = currentRenderId;
  27573. }
  27574. return this._batchCache;
  27575. };
  27576. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  27577. var visibleInstances = batch.visibleInstances[subMesh._id];
  27578. if (!visibleInstances) {
  27579. return this;
  27580. }
  27581. var matricesCount = visibleInstances.length + 1;
  27582. var bufferSize = matricesCount * 16 * 4;
  27583. var currentInstancesBufferSize = this._instancesBufferSize;
  27584. var instancesBuffer = this._instancesBuffer;
  27585. while (this._instancesBufferSize < bufferSize) {
  27586. this._instancesBufferSize *= 2;
  27587. }
  27588. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  27589. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  27590. }
  27591. var offset = 0;
  27592. var instancesCount = 0;
  27593. var world = this.getWorldMatrix();
  27594. if (batch.renderSelf[subMesh._id]) {
  27595. world.copyToArray(this._instancesData, offset);
  27596. offset += 16;
  27597. instancesCount++;
  27598. }
  27599. if (visibleInstances) {
  27600. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  27601. var instance = visibleInstances[instanceIndex];
  27602. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  27603. offset += 16;
  27604. instancesCount++;
  27605. }
  27606. }
  27607. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  27608. if (instancesBuffer) {
  27609. instancesBuffer.dispose();
  27610. }
  27611. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  27612. this._instancesBuffer = instancesBuffer;
  27613. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  27614. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  27615. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  27616. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  27617. }
  27618. else {
  27619. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  27620. }
  27621. this._bind(subMesh, effect, fillMode);
  27622. this._draw(subMesh, fillMode, instancesCount);
  27623. engine.unbindInstanceAttributes();
  27624. return this;
  27625. };
  27626. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  27627. var scene = this.getScene();
  27628. var engine = scene.getEngine();
  27629. if (hardwareInstancedRendering) {
  27630. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  27631. }
  27632. else {
  27633. if (batch.renderSelf[subMesh._id]) {
  27634. // Draw
  27635. if (onBeforeDraw) {
  27636. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  27637. }
  27638. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  27639. }
  27640. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  27641. if (visibleInstancesForSubMesh) {
  27642. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  27643. var instance = visibleInstancesForSubMesh[instanceIndex];
  27644. // World
  27645. var world = instance.getWorldMatrix();
  27646. if (onBeforeDraw) {
  27647. onBeforeDraw(true, world, effectiveMaterial);
  27648. }
  27649. // Draw
  27650. this._draw(subMesh, fillMode);
  27651. }
  27652. }
  27653. }
  27654. return this;
  27655. };
  27656. /**
  27657. * Triggers the draw call for the mesh.
  27658. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  27659. * Returns the Mesh.
  27660. */
  27661. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  27662. this.checkOcclusionQuery();
  27663. if (this._isOccluded) {
  27664. return this;
  27665. }
  27666. var scene = this.getScene();
  27667. // Managing instances
  27668. var batch = this._getInstancesRenderList(subMesh._id);
  27669. if (batch.mustReturn) {
  27670. return this;
  27671. }
  27672. // Checking geometry state
  27673. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27674. return this;
  27675. }
  27676. this.onBeforeRenderObservable.notifyObservers(this);
  27677. var engine = scene.getEngine();
  27678. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  27679. // Material
  27680. var material = subMesh.getMaterial();
  27681. if (!material) {
  27682. return this;
  27683. }
  27684. this._effectiveMaterial = material;
  27685. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27686. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27687. return this;
  27688. }
  27689. }
  27690. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  27691. return this;
  27692. }
  27693. // Alpha mode
  27694. if (enableAlphaMode) {
  27695. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  27696. }
  27697. // Outline - step 1
  27698. var savedDepthWrite = engine.getDepthWrite();
  27699. if (this.renderOutline) {
  27700. engine.setDepthWrite(false);
  27701. scene.getOutlineRenderer().render(subMesh, batch);
  27702. engine.setDepthWrite(savedDepthWrite);
  27703. }
  27704. var effect;
  27705. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27706. effect = subMesh.effect;
  27707. }
  27708. else {
  27709. effect = this._effectiveMaterial.getEffect();
  27710. }
  27711. if (!effect) {
  27712. return this;
  27713. }
  27714. var sideOrientation = this.overrideMaterialSideOrientation;
  27715. if (sideOrientation == null) {
  27716. sideOrientation = this._effectiveMaterial.sideOrientation;
  27717. if (this._getWorldMatrixDeterminant() < 0) {
  27718. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  27719. }
  27720. }
  27721. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  27722. if (this._effectiveMaterial.forceDepthWrite) {
  27723. engine.setDepthWrite(true);
  27724. }
  27725. // Bind
  27726. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  27727. if (!hardwareInstancedRendering) {
  27728. this._bind(subMesh, effect, fillMode);
  27729. }
  27730. var world = this.getWorldMatrix();
  27731. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27732. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  27733. }
  27734. else {
  27735. this._effectiveMaterial.bind(world, this);
  27736. }
  27737. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  27738. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  27739. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  27740. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  27741. }
  27742. // Draw
  27743. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  27744. // Unbind
  27745. this._effectiveMaterial.unbind();
  27746. // Outline - step 2
  27747. if (this.renderOutline && savedDepthWrite) {
  27748. engine.setDepthWrite(true);
  27749. engine.setColorWrite(false);
  27750. scene.getOutlineRenderer().render(subMesh, batch);
  27751. engine.setColorWrite(true);
  27752. }
  27753. // Overlay
  27754. if (this.renderOverlay) {
  27755. var currentMode = engine.getAlphaMode();
  27756. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27757. scene.getOutlineRenderer().render(subMesh, batch, true);
  27758. engine.setAlphaMode(currentMode);
  27759. }
  27760. this.onAfterRenderObservable.notifyObservers(this);
  27761. return this;
  27762. };
  27763. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  27764. if (isInstance && effectiveMaterial) {
  27765. effectiveMaterial.bindOnlyWorldMatrix(world);
  27766. }
  27767. };
  27768. /**
  27769. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  27770. */
  27771. Mesh.prototype.getEmittedParticleSystems = function () {
  27772. var results = new Array();
  27773. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27774. var particleSystem = this.getScene().particleSystems[index];
  27775. if (particleSystem.emitter === this) {
  27776. results.push(particleSystem);
  27777. }
  27778. }
  27779. return results;
  27780. };
  27781. /**
  27782. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  27783. */
  27784. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  27785. var results = new Array();
  27786. var descendants = this.getDescendants();
  27787. descendants.push(this);
  27788. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27789. var particleSystem = this.getScene().particleSystems[index];
  27790. var emitter = particleSystem.emitter;
  27791. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  27792. results.push(particleSystem);
  27793. }
  27794. }
  27795. return results;
  27796. };
  27797. Mesh.prototype._checkDelayState = function () {
  27798. var scene = this.getScene();
  27799. if (this._geometry) {
  27800. this._geometry.load(scene);
  27801. }
  27802. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27803. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27804. this._queueLoad(scene);
  27805. }
  27806. return this;
  27807. };
  27808. Mesh.prototype._queueLoad = function (scene) {
  27809. var _this = this;
  27810. scene._addPendingData(this);
  27811. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  27812. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27813. if (data instanceof ArrayBuffer) {
  27814. _this._delayLoadingFunction(data, _this);
  27815. }
  27816. else {
  27817. _this._delayLoadingFunction(JSON.parse(data), _this);
  27818. }
  27819. _this.instances.forEach(function (instance) {
  27820. instance._syncSubMeshes();
  27821. });
  27822. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27823. scene._removePendingData(_this);
  27824. }, function () { }, scene.database, getBinaryData);
  27825. return this;
  27826. };
  27827. /**
  27828. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  27829. */
  27830. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  27831. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27832. return false;
  27833. }
  27834. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  27835. return false;
  27836. }
  27837. this._checkDelayState();
  27838. return true;
  27839. };
  27840. /**
  27841. * Sets the mesh material by the material or multiMaterial `id` property.
  27842. * The material `id` is a string identifying the material or the multiMaterial.
  27843. * This method returns the Mesh.
  27844. */
  27845. Mesh.prototype.setMaterialByID = function (id) {
  27846. var materials = this.getScene().materials;
  27847. var index;
  27848. for (index = materials.length - 1; index > -1; index--) {
  27849. if (materials[index].id === id) {
  27850. this.material = materials[index];
  27851. return this;
  27852. }
  27853. }
  27854. // Multi
  27855. var multiMaterials = this.getScene().multiMaterials;
  27856. for (index = multiMaterials.length - 1; index > -1; index--) {
  27857. if (multiMaterials[index].id === id) {
  27858. this.material = multiMaterials[index];
  27859. return this;
  27860. }
  27861. }
  27862. return this;
  27863. };
  27864. /**
  27865. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  27866. */
  27867. Mesh.prototype.getAnimatables = function () {
  27868. var results = new Array();
  27869. if (this.material) {
  27870. results.push(this.material);
  27871. }
  27872. if (this.skeleton) {
  27873. results.push(this.skeleton);
  27874. }
  27875. return results;
  27876. };
  27877. /**
  27878. * Modifies the mesh geometry according to the passed transformation matrix.
  27879. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  27880. * The mesh normals are modified accordingly the same transformation.
  27881. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  27882. * Note that, under the hood, this method sets a new VertexBuffer each call.
  27883. * Returns the Mesh.
  27884. */
  27885. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  27886. // Position
  27887. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27888. return this;
  27889. }
  27890. var submeshes = this.subMeshes.splice(0);
  27891. this._resetPointsArrayCache();
  27892. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27893. var temp = new Array();
  27894. var index;
  27895. for (index = 0; index < data.length; index += 3) {
  27896. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  27897. }
  27898. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  27899. // Normals
  27900. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27901. return this;
  27902. }
  27903. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27904. temp = [];
  27905. for (index = 0; index < data.length; index += 3) {
  27906. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  27907. }
  27908. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  27909. // flip faces?
  27910. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  27911. this.flipFaces();
  27912. }
  27913. // Restore submeshes
  27914. this.releaseSubMeshes();
  27915. this.subMeshes = submeshes;
  27916. return this;
  27917. };
  27918. /**
  27919. * Modifies the mesh geometry according to its own current World Matrix.
  27920. * The mesh World Matrix is then reset.
  27921. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  27922. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  27923. * Note that, under the hood, this method sets a new VertexBuffer each call.
  27924. * Returns the Mesh.
  27925. */
  27926. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  27927. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  27928. this.scaling.copyFromFloats(1, 1, 1);
  27929. this.position.copyFromFloats(0, 0, 0);
  27930. this.rotation.copyFromFloats(0, 0, 0);
  27931. //only if quaternion is already set
  27932. if (this.rotationQuaternion) {
  27933. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  27934. }
  27935. this._worldMatrix = BABYLON.Matrix.Identity();
  27936. return this;
  27937. };
  27938. Object.defineProperty(Mesh.prototype, "_positions", {
  27939. // Cache
  27940. get: function () {
  27941. if (this._geometry) {
  27942. return this._geometry._positions;
  27943. }
  27944. return null;
  27945. },
  27946. enumerable: true,
  27947. configurable: true
  27948. });
  27949. Mesh.prototype._resetPointsArrayCache = function () {
  27950. if (this._geometry) {
  27951. this._geometry._resetPointsArrayCache();
  27952. }
  27953. return this;
  27954. };
  27955. Mesh.prototype._generatePointsArray = function () {
  27956. if (this._geometry) {
  27957. return this._geometry._generatePointsArray();
  27958. }
  27959. return false;
  27960. };
  27961. /**
  27962. * Returns a new Mesh object generated from the current mesh properties.
  27963. * This method must not get confused with createInstance().
  27964. * The parameter `name` is a string, the name given to the new mesh.
  27965. * The optional parameter `newParent` can be any Node object (default `null`).
  27966. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  27967. * 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.
  27968. */
  27969. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  27970. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27971. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  27972. };
  27973. /**
  27974. * Disposes the Mesh.
  27975. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  27976. * Returns nothing.
  27977. */
  27978. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  27979. var _this = this;
  27980. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  27981. this.morphTargetManager = null;
  27982. if (this._geometry) {
  27983. this._geometry.releaseForMesh(this, true);
  27984. }
  27985. // Sources
  27986. var meshes = this.getScene().meshes;
  27987. meshes.forEach(function (abstractMesh) {
  27988. var mesh = abstractMesh;
  27989. if (mesh._source && mesh._source === _this) {
  27990. mesh._source = null;
  27991. }
  27992. });
  27993. this._source = null;
  27994. // Instances
  27995. if (this._instancesBuffer) {
  27996. this._instancesBuffer.dispose();
  27997. this._instancesBuffer = null;
  27998. }
  27999. while (this.instances.length) {
  28000. this.instances[0].dispose();
  28001. }
  28002. // Highlight layers.
  28003. var highlightLayers = this.getScene().highlightLayers;
  28004. for (var i = 0; i < highlightLayers.length; i++) {
  28005. var highlightLayer = highlightLayers[i];
  28006. if (highlightLayer) {
  28007. highlightLayer.removeMesh(this);
  28008. highlightLayer.removeExcludedMesh(this);
  28009. }
  28010. }
  28011. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28012. };
  28013. /**
  28014. * Modifies the mesh geometry according to a displacement map.
  28015. * 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.
  28016. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28017. * This method returns nothing.
  28018. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28019. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28020. * 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.
  28021. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28022. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28023. *
  28024. * Returns the Mesh.
  28025. */
  28026. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28027. var _this = this;
  28028. var scene = this.getScene();
  28029. var onload = function (img) {
  28030. // Getting height map data
  28031. var canvas = document.createElement("canvas");
  28032. var context = canvas.getContext("2d");
  28033. var heightMapWidth = img.width;
  28034. var heightMapHeight = img.height;
  28035. canvas.width = heightMapWidth;
  28036. canvas.height = heightMapHeight;
  28037. context.drawImage(img, 0, 0);
  28038. // Create VertexData from map data
  28039. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28040. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28041. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28042. //execute success callback, if set
  28043. if (onSuccess) {
  28044. onSuccess(_this);
  28045. }
  28046. };
  28047. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28048. return this;
  28049. };
  28050. /**
  28051. * Modifies the mesh geometry according to a displacementMap buffer.
  28052. * 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.
  28053. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28054. * This method returns nothing.
  28055. * 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.
  28056. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28057. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28058. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28059. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28060. *
  28061. * Returns the Mesh.
  28062. */
  28063. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28064. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28065. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28066. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28067. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28068. return this;
  28069. }
  28070. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28071. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28072. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28073. var position = BABYLON.Vector3.Zero();
  28074. var normal = BABYLON.Vector3.Zero();
  28075. var uv = BABYLON.Vector2.Zero();
  28076. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28077. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28078. for (var index = 0; index < positions.length; index += 3) {
  28079. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28080. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28081. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28082. // Compute height
  28083. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28084. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28085. var pos = (u + v * heightMapWidth) * 4;
  28086. var r = buffer[pos] / 255.0;
  28087. var g = buffer[pos + 1] / 255.0;
  28088. var b = buffer[pos + 2] / 255.0;
  28089. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28090. normal.normalize();
  28091. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28092. position = position.add(normal);
  28093. position.toArray(positions, index);
  28094. }
  28095. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28096. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28097. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28098. return this;
  28099. };
  28100. /**
  28101. * Modify the mesh to get a flat shading rendering.
  28102. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28103. * This method returns the Mesh.
  28104. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28105. */
  28106. Mesh.prototype.convertToFlatShadedMesh = function () {
  28107. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  28108. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28109. var kinds = this.getVerticesDataKinds();
  28110. var vbs = {};
  28111. var data = {};
  28112. var newdata = {};
  28113. var updatableNormals = false;
  28114. var kindIndex;
  28115. var kind;
  28116. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28117. kind = kinds[kindIndex];
  28118. var vertexBuffer = this.getVertexBuffer(kind);
  28119. if (kind === BABYLON.VertexBuffer.NormalKind) {
  28120. updatableNormals = vertexBuffer.isUpdatable();
  28121. kinds.splice(kindIndex, 1);
  28122. kindIndex--;
  28123. continue;
  28124. }
  28125. vbs[kind] = vertexBuffer;
  28126. data[kind] = vbs[kind].getData();
  28127. newdata[kind] = [];
  28128. }
  28129. // Save previous submeshes
  28130. var previousSubmeshes = this.subMeshes.slice(0);
  28131. var indices = this.getIndices();
  28132. var totalIndices = this.getTotalIndices();
  28133. // Generating unique vertices per face
  28134. var index;
  28135. for (index = 0; index < totalIndices; index++) {
  28136. var vertexIndex = indices[index];
  28137. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28138. kind = kinds[kindIndex];
  28139. var stride = vbs[kind].getStrideSize();
  28140. for (var offset = 0; offset < stride; offset++) {
  28141. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28142. }
  28143. }
  28144. }
  28145. // Updating faces & normal
  28146. var normals = [];
  28147. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  28148. for (index = 0; index < totalIndices; index += 3) {
  28149. indices[index] = index;
  28150. indices[index + 1] = index + 1;
  28151. indices[index + 2] = index + 2;
  28152. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  28153. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  28154. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  28155. var p1p2 = p1.subtract(p2);
  28156. var p3p2 = p3.subtract(p2);
  28157. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  28158. // Store same normals for every vertex
  28159. for (var localIndex = 0; localIndex < 3; localIndex++) {
  28160. normals.push(normal.x);
  28161. normals.push(normal.y);
  28162. normals.push(normal.z);
  28163. }
  28164. }
  28165. this.setIndices(indices);
  28166. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  28167. // Updating vertex buffers
  28168. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28169. kind = kinds[kindIndex];
  28170. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28171. }
  28172. // Updating submeshes
  28173. this.releaseSubMeshes();
  28174. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28175. var previousOne = previousSubmeshes[submeshIndex];
  28176. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28177. }
  28178. this.synchronizeInstances();
  28179. return this;
  28180. };
  28181. /**
  28182. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  28183. * In other words, more vertices, no more indices and a single bigger VBO.
  28184. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  28185. * Returns the Mesh.
  28186. */
  28187. Mesh.prototype.convertToUnIndexedMesh = function () {
  28188. /// <summary>Remove indices by unfolding faces into buffers</summary>
  28189. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28190. var kinds = this.getVerticesDataKinds();
  28191. var vbs = {};
  28192. var data = {};
  28193. var newdata = {};
  28194. var kindIndex;
  28195. var kind;
  28196. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28197. kind = kinds[kindIndex];
  28198. var vertexBuffer = this.getVertexBuffer(kind);
  28199. vbs[kind] = vertexBuffer;
  28200. data[kind] = vbs[kind].getData();
  28201. newdata[kind] = [];
  28202. }
  28203. // Save previous submeshes
  28204. var previousSubmeshes = this.subMeshes.slice(0);
  28205. var indices = this.getIndices();
  28206. var totalIndices = this.getTotalIndices();
  28207. // Generating unique vertices per face
  28208. var index;
  28209. for (index = 0; index < totalIndices; index++) {
  28210. var vertexIndex = indices[index];
  28211. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28212. kind = kinds[kindIndex];
  28213. var stride = vbs[kind].getStrideSize();
  28214. for (var offset = 0; offset < stride; offset++) {
  28215. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28216. }
  28217. }
  28218. }
  28219. // Updating indices
  28220. for (index = 0; index < totalIndices; index += 3) {
  28221. indices[index] = index;
  28222. indices[index + 1] = index + 1;
  28223. indices[index + 2] = index + 2;
  28224. }
  28225. this.setIndices(indices);
  28226. // Updating vertex buffers
  28227. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28228. kind = kinds[kindIndex];
  28229. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28230. }
  28231. // Updating submeshes
  28232. this.releaseSubMeshes();
  28233. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28234. var previousOne = previousSubmeshes[submeshIndex];
  28235. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28236. }
  28237. this._unIndexed = true;
  28238. this.synchronizeInstances();
  28239. return this;
  28240. };
  28241. /**
  28242. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  28243. * This method returns the Mesh.
  28244. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  28245. */
  28246. Mesh.prototype.flipFaces = function (flipNormals) {
  28247. if (flipNormals === void 0) { flipNormals = false; }
  28248. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  28249. var i;
  28250. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  28251. for (i = 0; i < vertex_data.normals.length; i++) {
  28252. vertex_data.normals[i] *= -1;
  28253. }
  28254. }
  28255. if (vertex_data.indices) {
  28256. var temp;
  28257. for (i = 0; i < vertex_data.indices.length; i += 3) {
  28258. // reassign indices
  28259. temp = vertex_data.indices[i + 1];
  28260. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  28261. vertex_data.indices[i + 2] = temp;
  28262. }
  28263. }
  28264. vertex_data.applyToMesh(this);
  28265. return this;
  28266. };
  28267. // Instances
  28268. /**
  28269. * Creates a new InstancedMesh object from the mesh model.
  28270. * An instance shares the same properties and the same material than its model.
  28271. * Only these properties of each instance can then be set individually :
  28272. * - position
  28273. * - rotation
  28274. * - rotationQuaternion
  28275. * - setPivotMatrix
  28276. * - scaling
  28277. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  28278. * Warning : this method is not supported for Line mesh and LineSystem
  28279. */
  28280. Mesh.prototype.createInstance = function (name) {
  28281. return new BABYLON.InstancedMesh(name, this);
  28282. };
  28283. /**
  28284. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  28285. * After this call, all the mesh instances have the same submeshes than the current mesh.
  28286. * This method returns the Mesh.
  28287. */
  28288. Mesh.prototype.synchronizeInstances = function () {
  28289. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  28290. var instance = this.instances[instanceIndex];
  28291. instance._syncSubMeshes();
  28292. }
  28293. return this;
  28294. };
  28295. /**
  28296. * Simplify the mesh according to the given array of settings.
  28297. * Function will return immediately and will simplify async. It returns the Mesh.
  28298. * @param settings a collection of simplification settings.
  28299. * @param parallelProcessing should all levels calculate parallel or one after the other.
  28300. * @param type the type of simplification to run.
  28301. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  28302. */
  28303. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  28304. if (parallelProcessing === void 0) { parallelProcessing = true; }
  28305. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  28306. this.getScene().simplificationQueue.addTask({
  28307. settings: settings,
  28308. parallelProcessing: parallelProcessing,
  28309. mesh: this,
  28310. simplificationType: simplificationType,
  28311. successCallback: successCallback
  28312. });
  28313. return this;
  28314. };
  28315. /**
  28316. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  28317. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  28318. * This should be used together with the simplification to avoid disappearing triangles.
  28319. * Returns the Mesh.
  28320. * @param successCallback an optional success callback to be called after the optimization finished.
  28321. */
  28322. Mesh.prototype.optimizeIndices = function (successCallback) {
  28323. var _this = this;
  28324. var indices = this.getIndices();
  28325. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28326. if (!positions || !indices) {
  28327. return this;
  28328. }
  28329. var vectorPositions = new Array();
  28330. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  28331. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  28332. }
  28333. var dupes = new Array();
  28334. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  28335. var realPos = vectorPositions.length - 1 - iteration;
  28336. var testedPosition = vectorPositions[realPos];
  28337. for (var j = 0; j < realPos; ++j) {
  28338. var againstPosition = vectorPositions[j];
  28339. if (testedPosition.equals(againstPosition)) {
  28340. dupes[realPos] = j;
  28341. break;
  28342. }
  28343. }
  28344. }, function () {
  28345. for (var i = 0; i < indices.length; ++i) {
  28346. indices[i] = dupes[indices[i]] || indices[i];
  28347. }
  28348. //indices are now reordered
  28349. var originalSubMeshes = _this.subMeshes.slice(0);
  28350. _this.setIndices(indices);
  28351. _this.subMeshes = originalSubMeshes;
  28352. if (successCallback) {
  28353. successCallback(_this);
  28354. }
  28355. });
  28356. return this;
  28357. };
  28358. Mesh.prototype.serialize = function (serializationObject) {
  28359. serializationObject.name = this.name;
  28360. serializationObject.id = this.id;
  28361. serializationObject.type = this.getClassName();
  28362. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  28363. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28364. }
  28365. serializationObject.position = this.position.asArray();
  28366. if (this.rotationQuaternion) {
  28367. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  28368. }
  28369. else if (this.rotation) {
  28370. serializationObject.rotation = this.rotation.asArray();
  28371. }
  28372. serializationObject.scaling = this.scaling.asArray();
  28373. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  28374. serializationObject.isEnabled = this.isEnabled(false);
  28375. serializationObject.isVisible = this.isVisible;
  28376. serializationObject.infiniteDistance = this.infiniteDistance;
  28377. serializationObject.pickable = this.isPickable;
  28378. serializationObject.receiveShadows = this.receiveShadows;
  28379. serializationObject.billboardMode = this.billboardMode;
  28380. serializationObject.visibility = this.visibility;
  28381. serializationObject.checkCollisions = this.checkCollisions;
  28382. serializationObject.isBlocker = this.isBlocker;
  28383. // Parent
  28384. if (this.parent) {
  28385. serializationObject.parentId = this.parent.id;
  28386. }
  28387. // Geometry
  28388. serializationObject.isUnIndexed = this.isUnIndexed;
  28389. var geometry = this._geometry;
  28390. if (geometry) {
  28391. var geometryId = geometry.id;
  28392. serializationObject.geometryId = geometryId;
  28393. // SubMeshes
  28394. serializationObject.subMeshes = [];
  28395. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  28396. var subMesh = this.subMeshes[subIndex];
  28397. serializationObject.subMeshes.push({
  28398. materialIndex: subMesh.materialIndex,
  28399. verticesStart: subMesh.verticesStart,
  28400. verticesCount: subMesh.verticesCount,
  28401. indexStart: subMesh.indexStart,
  28402. indexCount: subMesh.indexCount
  28403. });
  28404. }
  28405. }
  28406. // Material
  28407. if (this.material) {
  28408. serializationObject.materialId = this.material.id;
  28409. }
  28410. else {
  28411. this.material = null;
  28412. }
  28413. // Morph targets
  28414. if (this.morphTargetManager) {
  28415. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  28416. }
  28417. // Skeleton
  28418. if (this.skeleton) {
  28419. serializationObject.skeletonId = this.skeleton.id;
  28420. }
  28421. // Physics
  28422. //TODO implement correct serialization for physics impostors.
  28423. var impostor = this.getPhysicsImpostor();
  28424. if (impostor) {
  28425. serializationObject.physicsMass = impostor.getParam("mass");
  28426. serializationObject.physicsFriction = impostor.getParam("friction");
  28427. serializationObject.physicsRestitution = impostor.getParam("mass");
  28428. serializationObject.physicsImpostor = impostor.type;
  28429. }
  28430. // Metadata
  28431. if (this.metadata) {
  28432. serializationObject.metadata = this.metadata;
  28433. }
  28434. // Instances
  28435. serializationObject.instances = [];
  28436. for (var index = 0; index < this.instances.length; index++) {
  28437. var instance = this.instances[index];
  28438. var serializationInstance = {
  28439. name: instance.name,
  28440. id: instance.id,
  28441. position: instance.position.asArray(),
  28442. scaling: instance.scaling.asArray()
  28443. };
  28444. if (instance.rotationQuaternion) {
  28445. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  28446. }
  28447. else if (instance.rotation) {
  28448. serializationInstance.rotation = instance.rotation.asArray();
  28449. }
  28450. serializationObject.instances.push(serializationInstance);
  28451. // Animations
  28452. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  28453. serializationInstance.ranges = instance.serializeAnimationRanges();
  28454. }
  28455. //
  28456. // Animations
  28457. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  28458. serializationObject.ranges = this.serializeAnimationRanges();
  28459. // Layer mask
  28460. serializationObject.layerMask = this.layerMask;
  28461. // Alpha
  28462. serializationObject.alphaIndex = this.alphaIndex;
  28463. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  28464. // Overlay
  28465. serializationObject.overlayAlpha = this.overlayAlpha;
  28466. serializationObject.overlayColor = this.overlayColor.asArray();
  28467. serializationObject.renderOverlay = this.renderOverlay;
  28468. // Fog
  28469. serializationObject.applyFog = this.applyFog;
  28470. // Action Manager
  28471. if (this.actionManager) {
  28472. serializationObject.actions = this.actionManager.serialize(this.name);
  28473. }
  28474. };
  28475. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  28476. if (!this.geometry) {
  28477. return;
  28478. }
  28479. this._markSubMeshesAsAttributesDirty();
  28480. var morphTargetManager = this._morphTargetManager;
  28481. if (morphTargetManager && morphTargetManager.vertexCount) {
  28482. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  28483. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  28484. this.morphTargetManager = null;
  28485. return;
  28486. }
  28487. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  28488. var morphTarget = morphTargetManager.getActiveTarget(index);
  28489. var positions = morphTarget.getPositions();
  28490. if (!positions) {
  28491. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  28492. return;
  28493. }
  28494. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  28495. var normals = morphTarget.getNormals();
  28496. if (normals) {
  28497. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  28498. }
  28499. var tangents = morphTarget.getTangents();
  28500. if (tangents) {
  28501. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  28502. }
  28503. }
  28504. }
  28505. else {
  28506. var index = 0;
  28507. // Positions
  28508. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  28509. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  28510. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  28511. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  28512. }
  28513. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  28514. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  28515. }
  28516. index++;
  28517. }
  28518. }
  28519. };
  28520. // Statics
  28521. /**
  28522. * Returns a new Mesh object parsed from the source provided.
  28523. * The parameter `parsedMesh` is the source.
  28524. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  28525. */
  28526. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  28527. var mesh;
  28528. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  28529. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  28530. }
  28531. else {
  28532. mesh = new Mesh(parsedMesh.name, scene);
  28533. }
  28534. mesh.id = parsedMesh.id;
  28535. if (BABYLON.Tags) {
  28536. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  28537. }
  28538. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  28539. if (parsedMesh.metadata !== undefined) {
  28540. mesh.metadata = parsedMesh.metadata;
  28541. }
  28542. if (parsedMesh.rotationQuaternion) {
  28543. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  28544. }
  28545. else if (parsedMesh.rotation) {
  28546. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  28547. }
  28548. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  28549. if (parsedMesh.localMatrix) {
  28550. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  28551. }
  28552. else if (parsedMesh.pivotMatrix) {
  28553. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  28554. }
  28555. mesh.setEnabled(parsedMesh.isEnabled);
  28556. mesh.isVisible = parsedMesh.isVisible;
  28557. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  28558. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  28559. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  28560. if (parsedMesh.applyFog !== undefined) {
  28561. mesh.applyFog = parsedMesh.applyFog;
  28562. }
  28563. if (parsedMesh.pickable !== undefined) {
  28564. mesh.isPickable = parsedMesh.pickable;
  28565. }
  28566. if (parsedMesh.alphaIndex !== undefined) {
  28567. mesh.alphaIndex = parsedMesh.alphaIndex;
  28568. }
  28569. mesh.receiveShadows = parsedMesh.receiveShadows;
  28570. mesh.billboardMode = parsedMesh.billboardMode;
  28571. if (parsedMesh.visibility !== undefined) {
  28572. mesh.visibility = parsedMesh.visibility;
  28573. }
  28574. mesh.checkCollisions = parsedMesh.checkCollisions;
  28575. if (parsedMesh.isBlocker !== undefined) {
  28576. mesh.isBlocker = parsedMesh.isBlocker;
  28577. }
  28578. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  28579. // freezeWorldMatrix
  28580. if (parsedMesh.freezeWorldMatrix) {
  28581. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  28582. }
  28583. // Parent
  28584. if (parsedMesh.parentId) {
  28585. mesh._waitingParentId = parsedMesh.parentId;
  28586. }
  28587. // Actions
  28588. if (parsedMesh.actions !== undefined) {
  28589. mesh._waitingActions = parsedMesh.actions;
  28590. }
  28591. // Overlay
  28592. if (parsedMesh.overlayAlpha !== undefined) {
  28593. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  28594. }
  28595. if (parsedMesh.overlayColor !== undefined) {
  28596. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  28597. }
  28598. if (parsedMesh.renderOverlay !== undefined) {
  28599. mesh.renderOverlay = parsedMesh.renderOverlay;
  28600. }
  28601. // Geometry
  28602. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  28603. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  28604. if (parsedMesh.delayLoadingFile) {
  28605. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28606. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  28607. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  28608. if (parsedMesh._binaryInfo) {
  28609. mesh._binaryInfo = parsedMesh._binaryInfo;
  28610. }
  28611. mesh._delayInfo = [];
  28612. if (parsedMesh.hasUVs) {
  28613. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  28614. }
  28615. if (parsedMesh.hasUVs2) {
  28616. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  28617. }
  28618. if (parsedMesh.hasUVs3) {
  28619. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  28620. }
  28621. if (parsedMesh.hasUVs4) {
  28622. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  28623. }
  28624. if (parsedMesh.hasUVs5) {
  28625. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  28626. }
  28627. if (parsedMesh.hasUVs6) {
  28628. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  28629. }
  28630. if (parsedMesh.hasColors) {
  28631. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  28632. }
  28633. if (parsedMesh.hasMatricesIndices) {
  28634. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28635. }
  28636. if (parsedMesh.hasMatricesWeights) {
  28637. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28638. }
  28639. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  28640. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  28641. mesh._checkDelayState();
  28642. }
  28643. }
  28644. else {
  28645. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  28646. }
  28647. // Material
  28648. if (parsedMesh.materialId) {
  28649. mesh.setMaterialByID(parsedMesh.materialId);
  28650. }
  28651. else {
  28652. mesh.material = null;
  28653. }
  28654. // Morph targets
  28655. if (parsedMesh.morphTargetManagerId > -1) {
  28656. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  28657. }
  28658. // Skeleton
  28659. if (parsedMesh.skeletonId > -1) {
  28660. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  28661. if (parsedMesh.numBoneInfluencers) {
  28662. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  28663. }
  28664. }
  28665. // Animations
  28666. if (parsedMesh.animations) {
  28667. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  28668. var parsedAnimation = parsedMesh.animations[animationIndex];
  28669. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28670. }
  28671. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  28672. }
  28673. if (parsedMesh.autoAnimate) {
  28674. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  28675. }
  28676. // Layer Mask
  28677. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  28678. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  28679. }
  28680. else {
  28681. mesh.layerMask = 0x0FFFFFFF;
  28682. }
  28683. // Physics
  28684. if (parsedMesh.physicsImpostor) {
  28685. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  28686. mass: parsedMesh.physicsMass,
  28687. friction: parsedMesh.physicsFriction,
  28688. restitution: parsedMesh.physicsRestitution
  28689. }, scene);
  28690. }
  28691. // Instances
  28692. if (parsedMesh.instances) {
  28693. for (var index = 0; index < parsedMesh.instances.length; index++) {
  28694. var parsedInstance = parsedMesh.instances[index];
  28695. var instance = mesh.createInstance(parsedInstance.name);
  28696. if (parsedInstance.id) {
  28697. instance.id = parsedInstance.id;
  28698. }
  28699. if (BABYLON.Tags) {
  28700. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  28701. }
  28702. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  28703. if (parsedInstance.parentId) {
  28704. instance._waitingParentId = parsedInstance.parentId;
  28705. }
  28706. if (parsedInstance.rotationQuaternion) {
  28707. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  28708. }
  28709. else if (parsedInstance.rotation) {
  28710. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  28711. }
  28712. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  28713. instance.checkCollisions = mesh.checkCollisions;
  28714. if (parsedMesh.animations) {
  28715. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  28716. parsedAnimation = parsedMesh.animations[animationIndex];
  28717. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28718. }
  28719. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  28720. }
  28721. }
  28722. }
  28723. return mesh;
  28724. };
  28725. /**
  28726. * Creates a ribbon mesh.
  28727. * Please consider using the same method from the MeshBuilder class instead.
  28728. * 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.
  28729. *
  28730. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  28731. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  28732. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  28733. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  28734. * 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.
  28735. * 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.
  28736. * 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
  28737. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28738. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28739. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28740. */
  28741. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  28742. if (closeArray === void 0) { closeArray = false; }
  28743. if (updatable === void 0) { updatable = false; }
  28744. return BABYLON.MeshBuilder.CreateRibbon(name, {
  28745. pathArray: pathArray,
  28746. closeArray: closeArray,
  28747. closePath: closePath,
  28748. offset: offset,
  28749. updatable: updatable,
  28750. sideOrientation: sideOrientation,
  28751. instance: instance
  28752. }, scene);
  28753. };
  28754. /**
  28755. * Creates a plane polygonal mesh. By default, this is a disc.
  28756. * Please consider using the same method from the MeshBuilder class instead.
  28757. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  28758. * 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.
  28759. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28760. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28761. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28762. */
  28763. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  28764. if (scene === void 0) { scene = null; }
  28765. var options = {
  28766. radius: radius,
  28767. tessellation: tessellation,
  28768. sideOrientation: sideOrientation,
  28769. updatable: updatable
  28770. };
  28771. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  28772. };
  28773. /**
  28774. * Creates a box mesh.
  28775. * Please consider using the same method from the MeshBuilder class instead.
  28776. * The parameter `size` sets the size (float) of each box side (default 1).
  28777. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28778. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28779. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28780. */
  28781. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  28782. if (scene === void 0) { scene = null; }
  28783. var options = {
  28784. size: size,
  28785. sideOrientation: sideOrientation,
  28786. updatable: updatable
  28787. };
  28788. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  28789. };
  28790. /**
  28791. * Creates a sphere mesh.
  28792. * Please consider using the same method from the MeshBuilder class instead.
  28793. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  28794. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  28795. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28796. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28797. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28798. */
  28799. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  28800. var options = {
  28801. segments: segments,
  28802. diameterX: diameter,
  28803. diameterY: diameter,
  28804. diameterZ: diameter,
  28805. sideOrientation: sideOrientation,
  28806. updatable: updatable
  28807. };
  28808. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  28809. };
  28810. /**
  28811. * Creates a cylinder or a cone mesh.
  28812. * Please consider using the same method from the MeshBuilder class instead.
  28813. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  28814. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  28815. * 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.
  28816. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  28817. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  28818. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28819. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28820. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28821. */
  28822. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  28823. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  28824. if (scene !== undefined) {
  28825. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  28826. updatable = scene;
  28827. }
  28828. scene = subdivisions;
  28829. subdivisions = 1;
  28830. }
  28831. var options = {
  28832. height: height,
  28833. diameterTop: diameterTop,
  28834. diameterBottom: diameterBottom,
  28835. tessellation: tessellation,
  28836. subdivisions: subdivisions,
  28837. sideOrientation: sideOrientation,
  28838. updatable: updatable
  28839. };
  28840. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  28841. };
  28842. // Torus (Code from SharpDX.org)
  28843. /**
  28844. * Creates a torus mesh.
  28845. * Please consider using the same method from the MeshBuilder class instead.
  28846. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  28847. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  28848. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  28849. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28850. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28851. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28852. */
  28853. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  28854. var options = {
  28855. diameter: diameter,
  28856. thickness: thickness,
  28857. tessellation: tessellation,
  28858. sideOrientation: sideOrientation,
  28859. updatable: updatable
  28860. };
  28861. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  28862. };
  28863. /**
  28864. * Creates a torus knot mesh.
  28865. * Please consider using the same method from the MeshBuilder class instead.
  28866. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  28867. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  28868. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  28869. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  28870. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28871. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28872. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28873. */
  28874. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  28875. var options = {
  28876. radius: radius,
  28877. tube: tube,
  28878. radialSegments: radialSegments,
  28879. tubularSegments: tubularSegments,
  28880. p: p,
  28881. q: q,
  28882. sideOrientation: sideOrientation,
  28883. updatable: updatable
  28884. };
  28885. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  28886. };
  28887. /**
  28888. * Creates a line mesh.
  28889. * Please consider using the same method from the MeshBuilder class instead.
  28890. * 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.
  28891. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28892. * The parameter `points` is an array successive Vector3.
  28893. * 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
  28894. * When updating an instance, remember that only point positions can change, not the number of points.
  28895. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28896. */
  28897. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  28898. if (scene === void 0) { scene = null; }
  28899. if (updatable === void 0) { updatable = false; }
  28900. if (instance === void 0) { instance = null; }
  28901. var options = {
  28902. points: points,
  28903. updatable: updatable,
  28904. instance: instance
  28905. };
  28906. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  28907. };
  28908. /**
  28909. * Creates a dashed line mesh.
  28910. * Please consider using the same method from the MeshBuilder class instead.
  28911. * 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.
  28912. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28913. * The parameter `points` is an array successive Vector3.
  28914. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  28915. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  28916. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  28917. * 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
  28918. * When updating an instance, remember that only point positions can change, not the number of points.
  28919. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28920. */
  28921. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  28922. if (scene === void 0) { scene = null; }
  28923. var options = {
  28924. points: points,
  28925. dashSize: dashSize,
  28926. gapSize: gapSize,
  28927. dashNb: dashNb,
  28928. updatable: updatable,
  28929. instance: instance
  28930. };
  28931. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  28932. };
  28933. /**
  28934. * Creates a polygon mesh.
  28935. * Please consider using the same method from the MeshBuilder class instead.
  28936. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  28937. * 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.
  28938. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28939. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28940. * Remember you can only change the shape positions, not their number when updating a polygon.
  28941. */
  28942. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  28943. var options = {
  28944. shape: shape,
  28945. holes: holes,
  28946. updatable: updatable,
  28947. sideOrientation: sideOrientation
  28948. };
  28949. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  28950. };
  28951. /**
  28952. * Creates an extruded polygon mesh, with depth in the Y direction.
  28953. * Please consider using the same method from the MeshBuilder class instead.
  28954. */
  28955. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  28956. var options = {
  28957. shape: shape,
  28958. holes: holes,
  28959. depth: depth,
  28960. updatable: updatable,
  28961. sideOrientation: sideOrientation
  28962. };
  28963. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  28964. };
  28965. /**
  28966. * Creates an extruded shape mesh.
  28967. * 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.
  28968. * Please consider using the same method from the MeshBuilder class instead.
  28969. *
  28970. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  28971. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  28972. * extruded along the Z axis.
  28973. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  28974. * The parameter `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.
  28975. * The parameter `scale` (float, default 1) is the value to scale the shape.
  28976. * 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
  28977. * 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
  28978. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  28979. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28980. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28981. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28982. */
  28983. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  28984. if (scene === void 0) { scene = null; }
  28985. var options = {
  28986. shape: shape,
  28987. path: path,
  28988. scale: scale,
  28989. rotation: rotation,
  28990. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  28991. sideOrientation: sideOrientation,
  28992. instance: instance,
  28993. updatable: updatable
  28994. };
  28995. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  28996. };
  28997. /**
  28998. * Creates an custom extruded shape mesh.
  28999. * 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.
  29000. * Please consider using the same method from the MeshBuilder class instead.
  29001. *
  29002. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29003. * 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
  29004. * extruded along the Z axis.
  29005. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29006. * 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
  29007. * and the distance of this point from the begining of the path :
  29008. * ```javascript
  29009. * var rotationFunction = function(i, distance) {
  29010. * // do things
  29011. * return rotationValue; }
  29012. * ```
  29013. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29014. * 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
  29015. * and the distance of this point from the begining of the path :
  29016. * ```javascript
  29017. * var scaleFunction = function(i, distance) {
  29018. * // do things
  29019. * return scaleValue;}
  29020. * ```
  29021. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29022. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29023. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29024. * 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
  29025. * 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
  29026. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29027. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29028. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29029. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29030. */
  29031. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29032. var options = {
  29033. shape: shape,
  29034. path: path,
  29035. scaleFunction: scaleFunction,
  29036. rotationFunction: rotationFunction,
  29037. ribbonCloseArray: ribbonCloseArray,
  29038. ribbonClosePath: ribbonClosePath,
  29039. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29040. sideOrientation: sideOrientation,
  29041. instance: instance,
  29042. updatable: updatable
  29043. };
  29044. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29045. };
  29046. /**
  29047. * Creates lathe mesh.
  29048. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29049. * Please consider using the same method from the MeshBuilder class instead.
  29050. * 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
  29051. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29052. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29053. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29054. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29055. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29056. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29057. */
  29058. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29059. var options = {
  29060. shape: shape,
  29061. radius: radius,
  29062. tessellation: tessellation,
  29063. sideOrientation: sideOrientation,
  29064. updatable: updatable
  29065. };
  29066. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29067. };
  29068. /**
  29069. * Creates a plane mesh.
  29070. * Please consider using the same method from the MeshBuilder class instead.
  29071. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29072. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29073. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29074. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29075. */
  29076. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29077. var options = {
  29078. size: size,
  29079. width: size,
  29080. height: size,
  29081. sideOrientation: sideOrientation,
  29082. updatable: updatable
  29083. };
  29084. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29085. };
  29086. /**
  29087. * Creates a ground mesh.
  29088. * Please consider using the same method from the MeshBuilder class instead.
  29089. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29090. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29091. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29092. */
  29093. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29094. var options = {
  29095. width: width,
  29096. height: height,
  29097. subdivisions: subdivisions,
  29098. updatable: updatable
  29099. };
  29100. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29101. };
  29102. /**
  29103. * Creates a tiled ground mesh.
  29104. * Please consider using the same method from the MeshBuilder class instead.
  29105. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29106. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29107. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29108. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29109. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29110. * numbers of subdivisions on the ground width and height of each tile.
  29111. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29112. */
  29113. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  29114. var options = {
  29115. xmin: xmin,
  29116. zmin: zmin,
  29117. xmax: xmax,
  29118. zmax: zmax,
  29119. subdivisions: subdivisions,
  29120. precision: precision,
  29121. updatable: updatable
  29122. };
  29123. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  29124. };
  29125. /**
  29126. * Creates a ground mesh from a height map.
  29127. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29128. * Please consider using the same method from the MeshBuilder class instead.
  29129. * The parameter `url` sets the URL of the height map image resource.
  29130. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29131. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29132. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29133. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29134. * 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).
  29135. * This function is passed the newly built mesh :
  29136. * ```javascript
  29137. * function(mesh) { // do things
  29138. * return; }
  29139. * ```
  29140. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29141. */
  29142. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  29143. var options = {
  29144. width: width,
  29145. height: height,
  29146. subdivisions: subdivisions,
  29147. minHeight: minHeight,
  29148. maxHeight: maxHeight,
  29149. updatable: updatable,
  29150. onReady: onReady
  29151. };
  29152. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  29153. };
  29154. /**
  29155. * Creates a tube mesh.
  29156. * 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.
  29157. * Please consider using the same method from the MeshBuilder class instead.
  29158. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29159. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29160. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29161. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29162. * 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.
  29163. * It must return a radius value (positive float) :
  29164. * ```javascript
  29165. * var radiusFunction = function(i, distance) {
  29166. * // do things
  29167. * return radius; }
  29168. * ```
  29169. * 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
  29170. * 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
  29171. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29172. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29173. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29174. */
  29175. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  29176. var options = {
  29177. path: path,
  29178. radius: radius,
  29179. tessellation: tessellation,
  29180. radiusFunction: radiusFunction,
  29181. arc: 1,
  29182. cap: cap,
  29183. updatable: updatable,
  29184. sideOrientation: sideOrientation,
  29185. instance: instance
  29186. };
  29187. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  29188. };
  29189. /**
  29190. * Creates a polyhedron mesh.
  29191. * Please consider using the same method from the MeshBuilder class instead.
  29192. * 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
  29193. * to choose the wanted type.
  29194. * The parameter `size` (positive float, default 1) sets the polygon size.
  29195. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  29196. * 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`.
  29197. * 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
  29198. * 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)`).
  29199. * 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
  29200. * 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.
  29201. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29202. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29203. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29204. */
  29205. Mesh.CreatePolyhedron = function (name, options, scene) {
  29206. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  29207. };
  29208. /**
  29209. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  29210. * Please consider using the same method from the MeshBuilder class instead.
  29211. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  29212. * 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`).
  29213. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  29214. * 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.
  29215. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29216. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29217. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29218. */
  29219. Mesh.CreateIcoSphere = function (name, options, scene) {
  29220. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  29221. };
  29222. /**
  29223. * Creates a decal mesh.
  29224. * Please consider using the same method from the MeshBuilder class instead.
  29225. * 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.
  29226. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  29227. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  29228. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  29229. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  29230. */
  29231. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  29232. var options = {
  29233. position: position,
  29234. normal: normal,
  29235. size: size,
  29236. angle: angle
  29237. };
  29238. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  29239. };
  29240. // Skeletons
  29241. /**
  29242. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29243. */
  29244. Mesh.prototype.setPositionsForCPUSkinning = function () {
  29245. if (!this._sourcePositions) {
  29246. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29247. if (!source) {
  29248. return this._sourcePositions;
  29249. }
  29250. this._sourcePositions = new Float32Array(source);
  29251. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  29252. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  29253. }
  29254. }
  29255. return this._sourcePositions;
  29256. };
  29257. /**
  29258. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29259. */
  29260. Mesh.prototype.setNormalsForCPUSkinning = function () {
  29261. if (!this._sourceNormals) {
  29262. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29263. if (!source) {
  29264. return this._sourceNormals;
  29265. }
  29266. this._sourceNormals = new Float32Array(source);
  29267. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  29268. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  29269. }
  29270. }
  29271. return this._sourceNormals;
  29272. };
  29273. /**
  29274. * Updates the vertex buffer by applying transformation from the bones.
  29275. * Returns the Mesh.
  29276. *
  29277. * @param {skeleton} skeleton to apply
  29278. */
  29279. Mesh.prototype.applySkeleton = function (skeleton) {
  29280. if (!this.geometry) {
  29281. return this;
  29282. }
  29283. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  29284. return this;
  29285. }
  29286. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  29287. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29288. return this;
  29289. }
  29290. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29291. return this;
  29292. }
  29293. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29294. return this;
  29295. }
  29296. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29297. return this;
  29298. }
  29299. if (!this._sourcePositions) {
  29300. var submeshes = this.subMeshes.slice();
  29301. this.setPositionsForCPUSkinning();
  29302. this.subMeshes = submeshes;
  29303. }
  29304. if (!this._sourceNormals) {
  29305. this.setNormalsForCPUSkinning();
  29306. }
  29307. // positionsData checks for not being Float32Array will only pass at most once
  29308. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29309. if (!positionsData) {
  29310. return this;
  29311. }
  29312. if (!(positionsData instanceof Float32Array)) {
  29313. positionsData = new Float32Array(positionsData);
  29314. }
  29315. // normalsData checks for not being Float32Array will only pass at most once
  29316. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29317. if (!normalsData) {
  29318. return this;
  29319. }
  29320. if (!(normalsData instanceof Float32Array)) {
  29321. normalsData = new Float32Array(normalsData);
  29322. }
  29323. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29324. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29325. if (!matricesWeightsData || !matricesIndicesData) {
  29326. return this;
  29327. }
  29328. var needExtras = this.numBoneInfluencers > 4;
  29329. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  29330. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  29331. var skeletonMatrices = skeleton.getTransformMatrices(this);
  29332. var tempVector3 = BABYLON.Vector3.Zero();
  29333. var finalMatrix = new BABYLON.Matrix();
  29334. var tempMatrix = new BABYLON.Matrix();
  29335. var matWeightIdx = 0;
  29336. var inf;
  29337. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  29338. var weight;
  29339. for (inf = 0; inf < 4; inf++) {
  29340. weight = matricesWeightsData[matWeightIdx + inf];
  29341. if (weight > 0) {
  29342. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  29343. finalMatrix.addToSelf(tempMatrix);
  29344. }
  29345. else
  29346. break;
  29347. }
  29348. if (needExtras) {
  29349. for (inf = 0; inf < 4; inf++) {
  29350. weight = matricesWeightsExtraData[matWeightIdx + inf];
  29351. if (weight > 0) {
  29352. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  29353. finalMatrix.addToSelf(tempMatrix);
  29354. }
  29355. else
  29356. break;
  29357. }
  29358. }
  29359. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  29360. tempVector3.toArray(positionsData, index);
  29361. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  29362. tempVector3.toArray(normalsData, index);
  29363. finalMatrix.reset();
  29364. }
  29365. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  29366. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  29367. return this;
  29368. };
  29369. // Tools
  29370. /**
  29371. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  29372. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  29373. */
  29374. Mesh.MinMax = function (meshes) {
  29375. var minVector = null;
  29376. var maxVector = null;
  29377. meshes.forEach(function (mesh, index, array) {
  29378. var boundingInfo = mesh.getBoundingInfo();
  29379. var boundingBox = boundingInfo.boundingBox;
  29380. if (!minVector || !maxVector) {
  29381. minVector = boundingBox.minimumWorld;
  29382. maxVector = boundingBox.maximumWorld;
  29383. }
  29384. else {
  29385. minVector.minimizeInPlace(boundingBox.minimumWorld);
  29386. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  29387. }
  29388. });
  29389. if (!minVector || !maxVector) {
  29390. return {
  29391. min: BABYLON.Vector3.Zero(),
  29392. max: BABYLON.Vector3.Zero()
  29393. };
  29394. }
  29395. return {
  29396. min: minVector,
  29397. max: maxVector
  29398. };
  29399. };
  29400. /**
  29401. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  29402. */
  29403. Mesh.Center = function (meshesOrMinMaxVector) {
  29404. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  29405. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  29406. };
  29407. /**
  29408. * Merge the array of meshes into a single mesh for performance reasons.
  29409. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  29410. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  29411. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  29412. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  29413. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  29414. */
  29415. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  29416. if (disposeSource === void 0) { disposeSource = true; }
  29417. var index;
  29418. if (!allow32BitsIndices) {
  29419. var totalVertices = 0;
  29420. // Counting vertices
  29421. for (index = 0; index < meshes.length; index++) {
  29422. if (meshes[index]) {
  29423. totalVertices += meshes[index].getTotalVertices();
  29424. if (totalVertices > 65536) {
  29425. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  29426. return null;
  29427. }
  29428. }
  29429. }
  29430. }
  29431. // Merge
  29432. var vertexData = null;
  29433. var otherVertexData;
  29434. var indiceArray = new Array();
  29435. var source = null;
  29436. for (index = 0; index < meshes.length; index++) {
  29437. if (meshes[index]) {
  29438. meshes[index].computeWorldMatrix(true);
  29439. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  29440. otherVertexData.transform(meshes[index].getWorldMatrix());
  29441. if (vertexData) {
  29442. vertexData.merge(otherVertexData);
  29443. }
  29444. else {
  29445. vertexData = otherVertexData;
  29446. source = meshes[index];
  29447. }
  29448. if (subdivideWithSubMeshes) {
  29449. indiceArray.push(meshes[index].getTotalIndices());
  29450. }
  29451. }
  29452. }
  29453. source = source;
  29454. if (!meshSubclass) {
  29455. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  29456. }
  29457. vertexData.applyToMesh(meshSubclass);
  29458. // Setting properties
  29459. meshSubclass.material = source.material;
  29460. meshSubclass.checkCollisions = source.checkCollisions;
  29461. // Cleaning
  29462. if (disposeSource) {
  29463. for (index = 0; index < meshes.length; index++) {
  29464. if (meshes[index]) {
  29465. meshes[index].dispose();
  29466. }
  29467. }
  29468. }
  29469. // Subdivide
  29470. if (subdivideWithSubMeshes) {
  29471. //-- Suppresions du submesh global
  29472. meshSubclass.releaseSubMeshes();
  29473. index = 0;
  29474. var offset = 0;
  29475. //-- aplique la subdivision en fonction du tableau d'indices
  29476. while (index < indiceArray.length) {
  29477. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  29478. offset += indiceArray[index];
  29479. index++;
  29480. }
  29481. }
  29482. return meshSubclass;
  29483. };
  29484. // Consts
  29485. Mesh._FRONTSIDE = 0;
  29486. Mesh._BACKSIDE = 1;
  29487. Mesh._DOUBLESIDE = 2;
  29488. Mesh._DEFAULTSIDE = 0;
  29489. Mesh._NO_CAP = 0;
  29490. Mesh._CAP_START = 1;
  29491. Mesh._CAP_END = 2;
  29492. Mesh._CAP_ALL = 3;
  29493. return Mesh;
  29494. }(BABYLON.AbstractMesh));
  29495. BABYLON.Mesh = Mesh;
  29496. })(BABYLON || (BABYLON = {}));
  29497. //# sourceMappingURL=babylon.mesh.js.map
  29498. var BABYLON;
  29499. (function (BABYLON) {
  29500. var BaseSubMesh = /** @class */ (function () {
  29501. function BaseSubMesh() {
  29502. }
  29503. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  29504. get: function () {
  29505. return this._materialEffect;
  29506. },
  29507. enumerable: true,
  29508. configurable: true
  29509. });
  29510. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  29511. if (defines === void 0) { defines = null; }
  29512. if (this._materialEffect === effect) {
  29513. if (!effect) {
  29514. this._materialDefines = null;
  29515. }
  29516. return;
  29517. }
  29518. this._materialDefines = defines;
  29519. this._materialEffect = effect;
  29520. };
  29521. return BaseSubMesh;
  29522. }());
  29523. BABYLON.BaseSubMesh = BaseSubMesh;
  29524. var SubMesh = /** @class */ (function (_super) {
  29525. __extends(SubMesh, _super);
  29526. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29527. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29528. var _this = _super.call(this) || this;
  29529. _this.materialIndex = materialIndex;
  29530. _this.verticesStart = verticesStart;
  29531. _this.verticesCount = verticesCount;
  29532. _this.indexStart = indexStart;
  29533. _this.indexCount = indexCount;
  29534. _this._renderId = 0;
  29535. _this._mesh = mesh;
  29536. _this._renderingMesh = renderingMesh || mesh;
  29537. mesh.subMeshes.push(_this);
  29538. _this._trianglePlanes = [];
  29539. _this._id = mesh.subMeshes.length - 1;
  29540. if (createBoundingBox) {
  29541. _this.refreshBoundingInfo();
  29542. mesh.computeWorldMatrix(true);
  29543. }
  29544. return _this;
  29545. }
  29546. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29547. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29548. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  29549. };
  29550. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  29551. get: function () {
  29552. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  29553. },
  29554. enumerable: true,
  29555. configurable: true
  29556. });
  29557. /**
  29558. * Returns the submesh BoudingInfo object.
  29559. */
  29560. SubMesh.prototype.getBoundingInfo = function () {
  29561. if (this.IsGlobal) {
  29562. return this._mesh.getBoundingInfo();
  29563. }
  29564. return this._boundingInfo;
  29565. };
  29566. /**
  29567. * Sets the submesh BoundingInfo.
  29568. * Return the SubMesh.
  29569. */
  29570. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  29571. this._boundingInfo = boundingInfo;
  29572. return this;
  29573. };
  29574. /**
  29575. * Returns the mesh of the current submesh.
  29576. */
  29577. SubMesh.prototype.getMesh = function () {
  29578. return this._mesh;
  29579. };
  29580. /**
  29581. * Returns the rendering mesh of the submesh.
  29582. */
  29583. SubMesh.prototype.getRenderingMesh = function () {
  29584. return this._renderingMesh;
  29585. };
  29586. /**
  29587. * Returns the submesh material.
  29588. */
  29589. SubMesh.prototype.getMaterial = function () {
  29590. var rootMaterial = this._renderingMesh.material;
  29591. if (rootMaterial === null || rootMaterial === undefined) {
  29592. return this._mesh.getScene().defaultMaterial;
  29593. }
  29594. else if (rootMaterial.getSubMaterial) {
  29595. var multiMaterial = rootMaterial;
  29596. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  29597. if (this._currentMaterial !== effectiveMaterial) {
  29598. this._currentMaterial = effectiveMaterial;
  29599. this._materialDefines = null;
  29600. }
  29601. return effectiveMaterial;
  29602. }
  29603. return rootMaterial;
  29604. };
  29605. // Methods
  29606. /**
  29607. * Sets a new updated BoundingInfo object to the submesh.
  29608. * Returns the SubMesh.
  29609. */
  29610. SubMesh.prototype.refreshBoundingInfo = function () {
  29611. this._lastColliderWorldVertices = null;
  29612. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  29613. return this;
  29614. }
  29615. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29616. if (!data) {
  29617. this._boundingInfo = this._mesh.getBoundingInfo();
  29618. return this;
  29619. }
  29620. var indices = this._renderingMesh.getIndices();
  29621. var extend;
  29622. //is this the only submesh?
  29623. if (this.indexStart === 0 && this.indexCount === indices.length) {
  29624. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29625. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  29626. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  29627. }
  29628. else {
  29629. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  29630. }
  29631. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29632. return this;
  29633. };
  29634. SubMesh.prototype._checkCollision = function (collider) {
  29635. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29636. return boundingInfo._checkCollision(collider);
  29637. };
  29638. /**
  29639. * Updates the submesh BoundingInfo.
  29640. * Returns the Submesh.
  29641. */
  29642. SubMesh.prototype.updateBoundingInfo = function (world) {
  29643. var boundingInfo = this.getBoundingInfo();
  29644. if (!boundingInfo) {
  29645. this.refreshBoundingInfo();
  29646. boundingInfo = this.getBoundingInfo();
  29647. }
  29648. boundingInfo.update(world);
  29649. return this;
  29650. };
  29651. /**
  29652. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  29653. * Boolean returned.
  29654. */
  29655. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  29656. var boundingInfo = this.getBoundingInfo();
  29657. if (!boundingInfo) {
  29658. return false;
  29659. }
  29660. return boundingInfo.isInFrustum(frustumPlanes);
  29661. };
  29662. /**
  29663. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  29664. * Boolean returned.
  29665. */
  29666. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  29667. var boundingInfo = this.getBoundingInfo();
  29668. if (!boundingInfo) {
  29669. return false;
  29670. }
  29671. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  29672. };
  29673. /**
  29674. * Renders the submesh.
  29675. * Returns it.
  29676. */
  29677. SubMesh.prototype.render = function (enableAlphaMode) {
  29678. this._renderingMesh.render(this, enableAlphaMode);
  29679. return this;
  29680. };
  29681. /**
  29682. * Returns a new Index Buffer.
  29683. * Type returned : WebGLBuffer.
  29684. */
  29685. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  29686. if (!this._linesIndexBuffer) {
  29687. var linesIndices = [];
  29688. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  29689. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  29690. }
  29691. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  29692. this.linesIndexCount = linesIndices.length;
  29693. }
  29694. return this._linesIndexBuffer;
  29695. };
  29696. /**
  29697. * True is the passed Ray intersects the submesh bounding box.
  29698. * Boolean returned.
  29699. */
  29700. SubMesh.prototype.canIntersects = function (ray) {
  29701. var boundingInfo = this.getBoundingInfo();
  29702. if (!boundingInfo) {
  29703. return false;
  29704. }
  29705. return ray.intersectsBox(boundingInfo.boundingBox);
  29706. };
  29707. /**
  29708. * Returns an object IntersectionInfo.
  29709. */
  29710. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  29711. var intersectInfo = null;
  29712. // LineMesh first as it's also a Mesh...
  29713. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  29714. var lineMesh = this._mesh;
  29715. // Line test
  29716. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  29717. var p0 = positions[indices[index]];
  29718. var p1 = positions[indices[index + 1]];
  29719. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  29720. if (length < 0) {
  29721. continue;
  29722. }
  29723. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  29724. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  29725. if (fastCheck) {
  29726. break;
  29727. }
  29728. }
  29729. }
  29730. }
  29731. else {
  29732. // Triangles test
  29733. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  29734. var p0 = positions[indices[index]];
  29735. var p1 = positions[indices[index + 1]];
  29736. var p2 = positions[indices[index + 2]];
  29737. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  29738. if (currentIntersectInfo) {
  29739. if (currentIntersectInfo.distance < 0) {
  29740. continue;
  29741. }
  29742. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  29743. intersectInfo = currentIntersectInfo;
  29744. intersectInfo.faceId = index / 3;
  29745. if (fastCheck) {
  29746. break;
  29747. }
  29748. }
  29749. }
  29750. }
  29751. }
  29752. return intersectInfo;
  29753. };
  29754. SubMesh.prototype._rebuild = function () {
  29755. if (this._linesIndexBuffer) {
  29756. this._linesIndexBuffer = null;
  29757. }
  29758. };
  29759. // Clone
  29760. /**
  29761. * Creates a new Submesh from the passed Mesh.
  29762. */
  29763. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  29764. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  29765. if (!this.IsGlobal) {
  29766. var boundingInfo = this.getBoundingInfo();
  29767. if (!boundingInfo) {
  29768. return result;
  29769. }
  29770. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  29771. }
  29772. return result;
  29773. };
  29774. // Dispose
  29775. /**
  29776. * Disposes the Submesh.
  29777. * Returns nothing.
  29778. */
  29779. SubMesh.prototype.dispose = function () {
  29780. if (this._linesIndexBuffer) {
  29781. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  29782. this._linesIndexBuffer = null;
  29783. }
  29784. // Remove from mesh
  29785. var index = this._mesh.subMeshes.indexOf(this);
  29786. this._mesh.subMeshes.splice(index, 1);
  29787. };
  29788. // Statics
  29789. /**
  29790. * Creates a new Submesh from the passed parameters :
  29791. * - materialIndex (integer) : the index of the main mesh material.
  29792. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  29793. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  29794. * - mesh (Mesh) : the main mesh to create the submesh from.
  29795. * - renderingMesh (optional Mesh) : rendering mesh.
  29796. */
  29797. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  29798. var minVertexIndex = Number.MAX_VALUE;
  29799. var maxVertexIndex = -Number.MAX_VALUE;
  29800. renderingMesh = (renderingMesh || mesh);
  29801. var indices = renderingMesh.getIndices();
  29802. for (var index = startIndex; index < startIndex + indexCount; index++) {
  29803. var vertexIndex = indices[index];
  29804. if (vertexIndex < minVertexIndex)
  29805. minVertexIndex = vertexIndex;
  29806. if (vertexIndex > maxVertexIndex)
  29807. maxVertexIndex = vertexIndex;
  29808. }
  29809. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  29810. };
  29811. return SubMesh;
  29812. }(BaseSubMesh));
  29813. BABYLON.SubMesh = SubMesh;
  29814. })(BABYLON || (BABYLON = {}));
  29815. //# sourceMappingURL=babylon.subMesh.js.map
  29816. var __assign = (this && this.__assign) || Object.assign || function(t) {
  29817. for (var s, i = 1, n = arguments.length; i < n; i++) {
  29818. s = arguments[i];
  29819. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  29820. t[p] = s[p];
  29821. }
  29822. return t;
  29823. };
  29824. var BABYLON;
  29825. (function (BABYLON) {
  29826. /**
  29827. * Manages the defines for the Material.
  29828. */
  29829. var MaterialDefines = /** @class */ (function () {
  29830. function MaterialDefines() {
  29831. this._isDirty = true;
  29832. this._areLightsDirty = true;
  29833. this._areAttributesDirty = true;
  29834. this._areTexturesDirty = true;
  29835. this._areFresnelDirty = true;
  29836. this._areMiscDirty = true;
  29837. this._areImageProcessingDirty = true;
  29838. this._normals = false;
  29839. this._uvs = false;
  29840. this._needNormals = false;
  29841. this._needUVs = false;
  29842. }
  29843. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  29844. /**
  29845. * Specifies if the material needs to be re-calculated.
  29846. */
  29847. get: function () {
  29848. return this._isDirty;
  29849. },
  29850. enumerable: true,
  29851. configurable: true
  29852. });
  29853. /**
  29854. * Marks the material to indicate that it has been re-calculated.
  29855. */
  29856. MaterialDefines.prototype.markAsProcessed = function () {
  29857. this._isDirty = false;
  29858. this._areAttributesDirty = false;
  29859. this._areTexturesDirty = false;
  29860. this._areFresnelDirty = false;
  29861. this._areLightsDirty = false;
  29862. this._areMiscDirty = false;
  29863. this._areImageProcessingDirty = false;
  29864. };
  29865. /**
  29866. * Marks the material to indicate that it needs to be re-calculated.
  29867. */
  29868. MaterialDefines.prototype.markAsUnprocessed = function () {
  29869. this._isDirty = true;
  29870. };
  29871. /**
  29872. * Marks the material to indicate all of its defines need to be re-calculated.
  29873. */
  29874. MaterialDefines.prototype.markAllAsDirty = function () {
  29875. this._areTexturesDirty = true;
  29876. this._areAttributesDirty = true;
  29877. this._areLightsDirty = true;
  29878. this._areFresnelDirty = true;
  29879. this._areMiscDirty = true;
  29880. this._areImageProcessingDirty = true;
  29881. this._isDirty = true;
  29882. };
  29883. /**
  29884. * Marks the material to indicate that image processing needs to be re-calculated.
  29885. */
  29886. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  29887. this._areImageProcessingDirty = true;
  29888. this._isDirty = true;
  29889. };
  29890. /**
  29891. * Marks the material to indicate the lights need to be re-calculated.
  29892. */
  29893. MaterialDefines.prototype.markAsLightDirty = function () {
  29894. this._areLightsDirty = true;
  29895. this._isDirty = true;
  29896. };
  29897. /**
  29898. * Marks the attribute state as changed.
  29899. */
  29900. MaterialDefines.prototype.markAsAttributesDirty = function () {
  29901. this._areAttributesDirty = true;
  29902. this._isDirty = true;
  29903. };
  29904. /**
  29905. * Marks the texture state as changed.
  29906. */
  29907. MaterialDefines.prototype.markAsTexturesDirty = function () {
  29908. this._areTexturesDirty = true;
  29909. this._isDirty = true;
  29910. };
  29911. /**
  29912. * Marks the fresnel state as changed.
  29913. */
  29914. MaterialDefines.prototype.markAsFresnelDirty = function () {
  29915. this._areFresnelDirty = true;
  29916. this._isDirty = true;
  29917. };
  29918. /**
  29919. * Marks the misc state as changed.
  29920. */
  29921. MaterialDefines.prototype.markAsMiscDirty = function () {
  29922. this._areMiscDirty = true;
  29923. this._isDirty = true;
  29924. };
  29925. /**
  29926. * Rebuilds the material defines.
  29927. */
  29928. MaterialDefines.prototype.rebuild = function () {
  29929. if (this._keys) {
  29930. delete this._keys;
  29931. }
  29932. this._keys = [];
  29933. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  29934. var key = _a[_i];
  29935. if (key[0] === "_") {
  29936. continue;
  29937. }
  29938. this._keys.push(key);
  29939. }
  29940. };
  29941. /**
  29942. * Specifies if two material defines are equal.
  29943. * @param other - A material define instance to compare to.
  29944. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  29945. */
  29946. MaterialDefines.prototype.isEqual = function (other) {
  29947. if (this._keys.length !== other._keys.length) {
  29948. return false;
  29949. }
  29950. for (var index = 0; index < this._keys.length; index++) {
  29951. var prop = this._keys[index];
  29952. if (this[prop] !== other[prop]) {
  29953. return false;
  29954. }
  29955. }
  29956. return true;
  29957. };
  29958. /**
  29959. * Clones this instance's defines to another instance.
  29960. * @param other - material defines to clone values to.
  29961. */
  29962. MaterialDefines.prototype.cloneTo = function (other) {
  29963. if (this._keys.length !== other._keys.length) {
  29964. other._keys = this._keys.slice(0);
  29965. }
  29966. for (var index = 0; index < this._keys.length; index++) {
  29967. var prop = this._keys[index];
  29968. other[prop] = this[prop];
  29969. }
  29970. };
  29971. /**
  29972. * Resets the material define values.
  29973. */
  29974. MaterialDefines.prototype.reset = function () {
  29975. for (var index = 0; index < this._keys.length; index++) {
  29976. var prop = this._keys[index];
  29977. if (typeof (this[prop]) === "number") {
  29978. this[prop] = 0;
  29979. }
  29980. else {
  29981. this[prop] = false;
  29982. }
  29983. }
  29984. };
  29985. /**
  29986. * Converts the material define values to a string.
  29987. * @returns - String of material define information.
  29988. */
  29989. MaterialDefines.prototype.toString = function () {
  29990. var result = "";
  29991. for (var index = 0; index < this._keys.length; index++) {
  29992. var prop = this._keys[index];
  29993. var value = this[prop];
  29994. if (typeof (value) === "number") {
  29995. result += "#define " + prop + " " + this[prop] + "\n";
  29996. }
  29997. else if (value) {
  29998. result += "#define " + prop + "\n";
  29999. }
  30000. }
  30001. return result;
  30002. };
  30003. return MaterialDefines;
  30004. }());
  30005. BABYLON.MaterialDefines = MaterialDefines;
  30006. /**
  30007. * This offers the main features of a material in BJS.
  30008. */
  30009. var Material = /** @class */ (function () {
  30010. /**
  30011. * Creates a material instance.
  30012. * @param name - The name of the material.
  30013. * @param scene - The BJS scene to reference.
  30014. * @param doNotAdd - Specifies if the material should be added to the scene.
  30015. */
  30016. function Material(name, scene, doNotAdd) {
  30017. /**
  30018. * Specifies if the ready state should be checked on each call.
  30019. */
  30020. this.checkReadyOnEveryCall = false;
  30021. /**
  30022. * Specifies if the ready state should be checked once.
  30023. */
  30024. this.checkReadyOnlyOnce = false;
  30025. /**
  30026. * The state of the material.
  30027. */
  30028. this.state = "";
  30029. /**
  30030. * The alpha value of the material.
  30031. */
  30032. this._alpha = 1.0;
  30033. /**
  30034. * Specifies if back face culling is enabled.
  30035. */
  30036. this._backFaceCulling = true;
  30037. /**
  30038. * Specifies if the material should be serialized.
  30039. */
  30040. this.doNotSerialize = false;
  30041. /**
  30042. * Specifies if the effect should be stored on sub meshes.
  30043. */
  30044. this.storeEffectOnSubMeshes = false;
  30045. /**
  30046. * An event triggered when the material is disposed.
  30047. * @type {BABYLON.Observable}
  30048. */
  30049. this.onDisposeObservable = new BABYLON.Observable();
  30050. /**
  30051. * An event triggered when the material is bound.
  30052. * @type {BABYLON.Observable}
  30053. */
  30054. this.onBindObservable = new BABYLON.Observable();
  30055. /**
  30056. * An event triggered when the material is unbound.
  30057. * @type {BABYLON.Observable}
  30058. */
  30059. this.onUnBindObservable = new BABYLON.Observable();
  30060. /**
  30061. * Stores the value of the alpha mode.
  30062. */
  30063. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30064. /**
  30065. * Stores the state of the need depth pre-pass value.
  30066. */
  30067. this._needDepthPrePass = false;
  30068. /**
  30069. * Specifies if depth writing should be disabled.
  30070. */
  30071. this.disableDepthWrite = false;
  30072. /**
  30073. * Specifies if depth writing should be forced.
  30074. */
  30075. this.forceDepthWrite = false;
  30076. /**
  30077. * Specifies if there should be a separate pass for culling.
  30078. */
  30079. this.separateCullingPass = false;
  30080. /**
  30081. * Stores the state specifing if fog should be enabled.
  30082. */
  30083. this._fogEnabled = true;
  30084. /**
  30085. * Stores the size of points.
  30086. */
  30087. this.pointSize = 1.0;
  30088. /**
  30089. * Stores the z offset value.
  30090. */
  30091. this.zOffset = 0;
  30092. /**
  30093. * Specifies if the material was previously ready.
  30094. */
  30095. this._wasPreviouslyReady = false;
  30096. /**
  30097. * Stores the fill mode state.
  30098. */
  30099. this._fillMode = Material.TriangleFillMode;
  30100. this.name = name;
  30101. this.id = name || BABYLON.Tools.RandomId();
  30102. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30103. if (this._scene.useRightHandedSystem) {
  30104. this.sideOrientation = Material.ClockWiseSideOrientation;
  30105. }
  30106. else {
  30107. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  30108. }
  30109. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  30110. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  30111. if (!doNotAdd) {
  30112. this._scene.materials.push(this);
  30113. }
  30114. }
  30115. Object.defineProperty(Material, "TriangleFillMode", {
  30116. /**
  30117. * Returns the triangle fill mode.
  30118. */
  30119. get: function () {
  30120. return Material._TriangleFillMode;
  30121. },
  30122. enumerable: true,
  30123. configurable: true
  30124. });
  30125. Object.defineProperty(Material, "WireFrameFillMode", {
  30126. /**
  30127. * Returns the wireframe mode.
  30128. */
  30129. get: function () {
  30130. return Material._WireFrameFillMode;
  30131. },
  30132. enumerable: true,
  30133. configurable: true
  30134. });
  30135. Object.defineProperty(Material, "PointFillMode", {
  30136. /**
  30137. * Returns the point fill mode.
  30138. */
  30139. get: function () {
  30140. return Material._PointFillMode;
  30141. },
  30142. enumerable: true,
  30143. configurable: true
  30144. });
  30145. Object.defineProperty(Material, "PointListDrawMode", {
  30146. /**
  30147. * Returns the point list draw mode.
  30148. */
  30149. get: function () {
  30150. return Material._PointListDrawMode;
  30151. },
  30152. enumerable: true,
  30153. configurable: true
  30154. });
  30155. Object.defineProperty(Material, "LineListDrawMode", {
  30156. /**
  30157. * Returns the line list draw mode.
  30158. */
  30159. get: function () {
  30160. return Material._LineListDrawMode;
  30161. },
  30162. enumerable: true,
  30163. configurable: true
  30164. });
  30165. Object.defineProperty(Material, "LineLoopDrawMode", {
  30166. /**
  30167. * Returns the line loop draw mode.
  30168. */
  30169. get: function () {
  30170. return Material._LineLoopDrawMode;
  30171. },
  30172. enumerable: true,
  30173. configurable: true
  30174. });
  30175. Object.defineProperty(Material, "LineStripDrawMode", {
  30176. /**
  30177. * Returns the line strip draw mode.
  30178. */
  30179. get: function () {
  30180. return Material._LineStripDrawMode;
  30181. },
  30182. enumerable: true,
  30183. configurable: true
  30184. });
  30185. Object.defineProperty(Material, "TriangleStripDrawMode", {
  30186. /**
  30187. * Returns the triangle strip draw mode.
  30188. */
  30189. get: function () {
  30190. return Material._TriangleStripDrawMode;
  30191. },
  30192. enumerable: true,
  30193. configurable: true
  30194. });
  30195. Object.defineProperty(Material, "TriangleFanDrawMode", {
  30196. /**
  30197. * Returns the triangle fan draw mode.
  30198. */
  30199. get: function () {
  30200. return Material._TriangleFanDrawMode;
  30201. },
  30202. enumerable: true,
  30203. configurable: true
  30204. });
  30205. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  30206. /**
  30207. * Returns the clock-wise side orientation.
  30208. */
  30209. get: function () {
  30210. return Material._ClockWiseSideOrientation;
  30211. },
  30212. enumerable: true,
  30213. configurable: true
  30214. });
  30215. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  30216. /**
  30217. * Returns the counter clock-wise side orientation.
  30218. */
  30219. get: function () {
  30220. return Material._CounterClockWiseSideOrientation;
  30221. },
  30222. enumerable: true,
  30223. configurable: true
  30224. });
  30225. Object.defineProperty(Material, "TextureDirtyFlag", {
  30226. /**
  30227. * Returns the dirty texture flag value.
  30228. */
  30229. get: function () {
  30230. return Material._TextureDirtyFlag;
  30231. },
  30232. enumerable: true,
  30233. configurable: true
  30234. });
  30235. Object.defineProperty(Material, "LightDirtyFlag", {
  30236. /**
  30237. * Returns the dirty light flag value.
  30238. */
  30239. get: function () {
  30240. return Material._LightDirtyFlag;
  30241. },
  30242. enumerable: true,
  30243. configurable: true
  30244. });
  30245. Object.defineProperty(Material, "FresnelDirtyFlag", {
  30246. /**
  30247. * Returns the dirty fresnel flag value.
  30248. */
  30249. get: function () {
  30250. return Material._FresnelDirtyFlag;
  30251. },
  30252. enumerable: true,
  30253. configurable: true
  30254. });
  30255. Object.defineProperty(Material, "AttributesDirtyFlag", {
  30256. /**
  30257. * Returns the dirty attributes flag value.
  30258. */
  30259. get: function () {
  30260. return Material._AttributesDirtyFlag;
  30261. },
  30262. enumerable: true,
  30263. configurable: true
  30264. });
  30265. Object.defineProperty(Material, "MiscDirtyFlag", {
  30266. /**
  30267. * Returns the dirty misc flag value.
  30268. */
  30269. get: function () {
  30270. return Material._MiscDirtyFlag;
  30271. },
  30272. enumerable: true,
  30273. configurable: true
  30274. });
  30275. Object.defineProperty(Material.prototype, "alpha", {
  30276. /**
  30277. * Gets the alpha value of the material.
  30278. */
  30279. get: function () {
  30280. return this._alpha;
  30281. },
  30282. /**
  30283. * Sets the alpha value of the material.
  30284. */
  30285. set: function (value) {
  30286. if (this._alpha === value) {
  30287. return;
  30288. }
  30289. this._alpha = value;
  30290. this.markAsDirty(Material.MiscDirtyFlag);
  30291. },
  30292. enumerable: true,
  30293. configurable: true
  30294. });
  30295. Object.defineProperty(Material.prototype, "backFaceCulling", {
  30296. /**
  30297. * Gets the back-face culling state.
  30298. */
  30299. get: function () {
  30300. return this._backFaceCulling;
  30301. },
  30302. /**
  30303. * Sets the back-face culling state.
  30304. */
  30305. set: function (value) {
  30306. if (this._backFaceCulling === value) {
  30307. return;
  30308. }
  30309. this._backFaceCulling = value;
  30310. this.markAsDirty(Material.TextureDirtyFlag);
  30311. },
  30312. enumerable: true,
  30313. configurable: true
  30314. });
  30315. Object.defineProperty(Material.prototype, "onDispose", {
  30316. /**
  30317. * Called during a dispose event.
  30318. */
  30319. set: function (callback) {
  30320. if (this._onDisposeObserver) {
  30321. this.onDisposeObservable.remove(this._onDisposeObserver);
  30322. }
  30323. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30324. },
  30325. enumerable: true,
  30326. configurable: true
  30327. });
  30328. Object.defineProperty(Material.prototype, "onBind", {
  30329. /**
  30330. * Called during a bind event.
  30331. */
  30332. set: function (callback) {
  30333. if (this._onBindObserver) {
  30334. this.onBindObservable.remove(this._onBindObserver);
  30335. }
  30336. this._onBindObserver = this.onBindObservable.add(callback);
  30337. },
  30338. enumerable: true,
  30339. configurable: true
  30340. });
  30341. Object.defineProperty(Material.prototype, "alphaMode", {
  30342. /**
  30343. * Gets the value of the alpha mode.
  30344. */
  30345. get: function () {
  30346. return this._alphaMode;
  30347. },
  30348. /**
  30349. * Sets the value of the alpha mode.
  30350. */
  30351. set: function (value) {
  30352. if (this._alphaMode === value) {
  30353. return;
  30354. }
  30355. this._alphaMode = value;
  30356. this.markAsDirty(Material.TextureDirtyFlag);
  30357. },
  30358. enumerable: true,
  30359. configurable: true
  30360. });
  30361. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  30362. /**
  30363. * Gets the depth pre-pass value.
  30364. */
  30365. get: function () {
  30366. return this._needDepthPrePass;
  30367. },
  30368. /**
  30369. * Sets the need depth pre-pass value.
  30370. */
  30371. set: function (value) {
  30372. if (this._needDepthPrePass === value) {
  30373. return;
  30374. }
  30375. this._needDepthPrePass = value;
  30376. if (this._needDepthPrePass) {
  30377. this.checkReadyOnEveryCall = true;
  30378. }
  30379. },
  30380. enumerable: true,
  30381. configurable: true
  30382. });
  30383. Object.defineProperty(Material.prototype, "fogEnabled", {
  30384. /**
  30385. * Gets the value of the fog enabled state.
  30386. */
  30387. get: function () {
  30388. return this._fogEnabled;
  30389. },
  30390. /**
  30391. * Sets the state for enabling fog.
  30392. */
  30393. set: function (value) {
  30394. if (this._fogEnabled === value) {
  30395. return;
  30396. }
  30397. this._fogEnabled = value;
  30398. this.markAsDirty(Material.MiscDirtyFlag);
  30399. },
  30400. enumerable: true,
  30401. configurable: true
  30402. });
  30403. Object.defineProperty(Material.prototype, "wireframe", {
  30404. /**
  30405. * Gets a value specifying if wireframe mode is enabled.
  30406. */
  30407. get: function () {
  30408. return this._fillMode === Material.WireFrameFillMode;
  30409. },
  30410. /**
  30411. * Sets the state of wireframe mode.
  30412. */
  30413. set: function (value) {
  30414. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  30415. },
  30416. enumerable: true,
  30417. configurable: true
  30418. });
  30419. Object.defineProperty(Material.prototype, "pointsCloud", {
  30420. /**
  30421. * Gets the value specifying if point clouds are enabled.
  30422. */
  30423. get: function () {
  30424. return this._fillMode === Material.PointFillMode;
  30425. },
  30426. /**
  30427. * Sets the state of point cloud mode.
  30428. */
  30429. set: function (value) {
  30430. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  30431. },
  30432. enumerable: true,
  30433. configurable: true
  30434. });
  30435. Object.defineProperty(Material.prototype, "fillMode", {
  30436. /**
  30437. * Gets the material fill mode.
  30438. */
  30439. get: function () {
  30440. return this._fillMode;
  30441. },
  30442. /**
  30443. * Sets the material fill mode.
  30444. */
  30445. set: function (value) {
  30446. if (this._fillMode === value) {
  30447. return;
  30448. }
  30449. this._fillMode = value;
  30450. this.markAsDirty(Material.MiscDirtyFlag);
  30451. },
  30452. enumerable: true,
  30453. configurable: true
  30454. });
  30455. /**
  30456. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30457. * subclasses should override adding information pertainent to themselves.
  30458. * @returns - String with material information.
  30459. */
  30460. Material.prototype.toString = function (fullDetails) {
  30461. var ret = "Name: " + this.name;
  30462. if (fullDetails) {
  30463. }
  30464. return ret;
  30465. };
  30466. /**
  30467. * Gets the class name of the material.
  30468. * @returns - String with the class name of the material.
  30469. */
  30470. Material.prototype.getClassName = function () {
  30471. return "Material";
  30472. };
  30473. Object.defineProperty(Material.prototype, "isFrozen", {
  30474. /**
  30475. * Specifies if updates for the material been locked.
  30476. */
  30477. get: function () {
  30478. return this.checkReadyOnlyOnce;
  30479. },
  30480. enumerable: true,
  30481. configurable: true
  30482. });
  30483. /**
  30484. * Locks updates for the material.
  30485. */
  30486. Material.prototype.freeze = function () {
  30487. this.checkReadyOnlyOnce = true;
  30488. };
  30489. /**
  30490. * Unlocks updates for the material.
  30491. */
  30492. Material.prototype.unfreeze = function () {
  30493. this.checkReadyOnlyOnce = false;
  30494. };
  30495. /**
  30496. * Specifies if the material is ready to be used.
  30497. * @param mesh - BJS mesh.
  30498. * @param useInstances - Specifies if instances should be used.
  30499. * @returns - Boolean indicating if the material is ready to be used.
  30500. */
  30501. Material.prototype.isReady = function (mesh, useInstances) {
  30502. return true;
  30503. };
  30504. /**
  30505. * Specifies that the submesh is ready to be used.
  30506. * @param mesh - BJS mesh.
  30507. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  30508. * @param useInstances - Specifies that instances should be used.
  30509. * @returns - boolean indicating that the submesh is ready or not.
  30510. */
  30511. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30512. return false;
  30513. };
  30514. /**
  30515. * Returns the material effect.
  30516. * @returns - Nullable material effect.
  30517. */
  30518. Material.prototype.getEffect = function () {
  30519. return this._effect;
  30520. };
  30521. /**
  30522. * Returns the BJS scene.
  30523. * @returns - BJS Scene.
  30524. */
  30525. Material.prototype.getScene = function () {
  30526. return this._scene;
  30527. };
  30528. /**
  30529. * Specifies if the material will require alpha blending
  30530. * @returns - Boolean specifying if alpha blending is needed.
  30531. */
  30532. Material.prototype.needAlphaBlending = function () {
  30533. return (this.alpha < 1.0);
  30534. };
  30535. /**
  30536. * Specifies if the mesh will require alpha blending.
  30537. * @param mesh - BJS mesh.
  30538. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  30539. */
  30540. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  30541. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  30542. };
  30543. /**
  30544. * Specifies if this material should be rendered in alpha test mode.
  30545. * @returns - Boolean specifying if an alpha test is needed.
  30546. */
  30547. Material.prototype.needAlphaTesting = function () {
  30548. return false;
  30549. };
  30550. /**
  30551. * Gets the texture used for the alpha test.
  30552. * @returns - Nullable alpha test texture.
  30553. */
  30554. Material.prototype.getAlphaTestTexture = function () {
  30555. return null;
  30556. };
  30557. /**
  30558. * Marks the material to indicate that it needs to be re-calculated.
  30559. */
  30560. Material.prototype.markDirty = function () {
  30561. this._wasPreviouslyReady = false;
  30562. };
  30563. Material.prototype._preBind = function (effect, overrideOrientation) {
  30564. if (overrideOrientation === void 0) { overrideOrientation = null; }
  30565. var engine = this._scene.getEngine();
  30566. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  30567. var reverse = orientation === Material.ClockWiseSideOrientation;
  30568. engine.enableEffect(effect ? effect : this._effect);
  30569. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  30570. return reverse;
  30571. };
  30572. /**
  30573. * Binds the material to the mesh.
  30574. * @param world - World transformation matrix.
  30575. * @param mesh - Mesh to bind the material to.
  30576. */
  30577. Material.prototype.bind = function (world, mesh) {
  30578. };
  30579. /**
  30580. * Binds the submesh to the material.
  30581. * @param world - World transformation matrix.
  30582. * @param mesh - Mesh containing the submesh.
  30583. * @param subMesh - Submesh to bind the material to.
  30584. */
  30585. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  30586. };
  30587. /**
  30588. * Binds the world matrix to the material.
  30589. * @param world - World transformation matrix.
  30590. */
  30591. Material.prototype.bindOnlyWorldMatrix = function (world) {
  30592. };
  30593. /**
  30594. * Binds the scene's uniform buffer to the effect.
  30595. * @param effect - Effect to bind to the scene uniform buffer.
  30596. * @param sceneUbo - Scene uniform buffer.
  30597. */
  30598. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  30599. sceneUbo.bindToEffect(effect, "Scene");
  30600. };
  30601. /**
  30602. * Binds the view matrix to the effect.
  30603. * @param effect - Effect to bind the view matrix to.
  30604. */
  30605. Material.prototype.bindView = function (effect) {
  30606. if (!this._useUBO) {
  30607. effect.setMatrix("view", this.getScene().getViewMatrix());
  30608. }
  30609. else {
  30610. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  30611. }
  30612. };
  30613. /**
  30614. * Binds the view projection matrix to the effect.
  30615. * @param effect - Effect to bind the view projection matrix to.
  30616. */
  30617. Material.prototype.bindViewProjection = function (effect) {
  30618. if (!this._useUBO) {
  30619. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  30620. }
  30621. else {
  30622. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  30623. }
  30624. };
  30625. /**
  30626. * Specifies if material alpha testing should be turned on for the mesh.
  30627. * @param mesh - BJS mesh.
  30628. */
  30629. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  30630. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  30631. };
  30632. /**
  30633. * Processes to execute after binding the material to a mesh.
  30634. * @param mesh - BJS mesh.
  30635. */
  30636. Material.prototype._afterBind = function (mesh) {
  30637. this._scene._cachedMaterial = this;
  30638. if (mesh) {
  30639. this._scene._cachedVisibility = mesh.visibility;
  30640. }
  30641. else {
  30642. this._scene._cachedVisibility = 1;
  30643. }
  30644. if (mesh) {
  30645. this.onBindObservable.notifyObservers(mesh);
  30646. }
  30647. if (this.disableDepthWrite) {
  30648. var engine = this._scene.getEngine();
  30649. this._cachedDepthWriteState = engine.getDepthWrite();
  30650. engine.setDepthWrite(false);
  30651. }
  30652. };
  30653. /**
  30654. * Unbinds the material from the mesh.
  30655. */
  30656. Material.prototype.unbind = function () {
  30657. this.onUnBindObservable.notifyObservers(this);
  30658. if (this.disableDepthWrite) {
  30659. var engine = this._scene.getEngine();
  30660. engine.setDepthWrite(this._cachedDepthWriteState);
  30661. }
  30662. };
  30663. /**
  30664. * Gets the active textures from the material.
  30665. * @returns - Array of textures.
  30666. */
  30667. Material.prototype.getActiveTextures = function () {
  30668. return [];
  30669. };
  30670. /**
  30671. * Specifies if the material uses a texture.
  30672. * @param texture - Texture to check against the material.
  30673. * @returns - Boolean specifying if the material uses the texture.
  30674. */
  30675. Material.prototype.hasTexture = function (texture) {
  30676. return false;
  30677. };
  30678. /**
  30679. * Makes a duplicate of the material, and gives it a new name.
  30680. * @param name - Name to call the duplicated material.
  30681. * @returns - Nullable cloned material
  30682. */
  30683. Material.prototype.clone = function (name) {
  30684. return null;
  30685. };
  30686. /**
  30687. * Gets the meshes bound to the material.
  30688. * @returns - Array of meshes bound to the material.
  30689. */
  30690. Material.prototype.getBindedMeshes = function () {
  30691. var result = new Array();
  30692. for (var index = 0; index < this._scene.meshes.length; index++) {
  30693. var mesh = this._scene.meshes[index];
  30694. if (mesh.material === this) {
  30695. result.push(mesh);
  30696. }
  30697. }
  30698. return result;
  30699. };
  30700. /**
  30701. * Force shader compilation including textures ready check
  30702. * @param mesh - BJS mesh.
  30703. * @param onCompiled - function to execute once the material is compiled.
  30704. * @param options - options to pass to this function.
  30705. */
  30706. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  30707. var _this = this;
  30708. var localOptions = __assign({ clipPlane: false }, options);
  30709. var subMesh = new BABYLON.BaseSubMesh();
  30710. var scene = this.getScene();
  30711. var checkReady = function () {
  30712. if (!_this._scene || !_this._scene.getEngine()) {
  30713. return;
  30714. }
  30715. if (subMesh._materialDefines) {
  30716. subMesh._materialDefines._renderId = -1;
  30717. }
  30718. var clipPlaneState = scene.clipPlane;
  30719. if (localOptions.clipPlane) {
  30720. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  30721. }
  30722. if (_this.storeEffectOnSubMeshes) {
  30723. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  30724. if (onCompiled) {
  30725. onCompiled(_this);
  30726. }
  30727. }
  30728. else {
  30729. setTimeout(checkReady, 16);
  30730. }
  30731. }
  30732. else {
  30733. if (_this.isReady(mesh)) {
  30734. if (onCompiled) {
  30735. onCompiled(_this);
  30736. }
  30737. }
  30738. else {
  30739. setTimeout(checkReady, 16);
  30740. }
  30741. }
  30742. if (options && options.clipPlane) {
  30743. scene.clipPlane = clipPlaneState;
  30744. }
  30745. };
  30746. checkReady();
  30747. };
  30748. /**
  30749. * Marks a define in the material to indicate that it needs to be re-computed.
  30750. * @param flag - Material define flag.
  30751. */
  30752. Material.prototype.markAsDirty = function (flag) {
  30753. if (flag & Material.TextureDirtyFlag) {
  30754. this._markAllSubMeshesAsTexturesDirty();
  30755. }
  30756. if (flag & Material.LightDirtyFlag) {
  30757. this._markAllSubMeshesAsLightsDirty();
  30758. }
  30759. if (flag & Material.FresnelDirtyFlag) {
  30760. this._markAllSubMeshesAsFresnelDirty();
  30761. }
  30762. if (flag & Material.AttributesDirtyFlag) {
  30763. this._markAllSubMeshesAsAttributesDirty();
  30764. }
  30765. if (flag & Material.MiscDirtyFlag) {
  30766. this._markAllSubMeshesAsMiscDirty();
  30767. }
  30768. this.getScene().resetCachedMaterial();
  30769. };
  30770. /**
  30771. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  30772. * @param func - function which checks material defines against the submeshes.
  30773. */
  30774. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  30775. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  30776. var mesh = _a[_i];
  30777. if (!mesh.subMeshes) {
  30778. continue;
  30779. }
  30780. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  30781. var subMesh = _c[_b];
  30782. if (subMesh.getMaterial() !== this) {
  30783. continue;
  30784. }
  30785. if (!subMesh._materialDefines) {
  30786. continue;
  30787. }
  30788. func(subMesh._materialDefines);
  30789. }
  30790. }
  30791. };
  30792. /**
  30793. * Indicates that image processing needs to be re-calculated for all submeshes.
  30794. */
  30795. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  30796. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  30797. };
  30798. /**
  30799. * Indicates that textures need to be re-calculated for all submeshes.
  30800. */
  30801. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  30802. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  30803. };
  30804. /**
  30805. * Indicates that fresnel needs to be re-calculated for all submeshes.
  30806. */
  30807. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  30808. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  30809. };
  30810. /**
  30811. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  30812. */
  30813. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  30814. this._markAllSubMeshesAsDirty(function (defines) {
  30815. defines.markAsFresnelDirty();
  30816. defines.markAsMiscDirty();
  30817. });
  30818. };
  30819. /**
  30820. * Indicates that lights need to be re-calculated for all submeshes.
  30821. */
  30822. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  30823. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  30824. };
  30825. /**
  30826. * Indicates that attributes need to be re-calculated for all submeshes.
  30827. */
  30828. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  30829. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  30830. };
  30831. /**
  30832. * Indicates that misc needs to be re-calculated for all submeshes.
  30833. */
  30834. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  30835. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  30836. };
  30837. /**
  30838. * Indicates that textures and misc need to be re-calculated for all submeshes.
  30839. */
  30840. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  30841. this._markAllSubMeshesAsDirty(function (defines) {
  30842. defines.markAsTexturesDirty();
  30843. defines.markAsMiscDirty();
  30844. });
  30845. };
  30846. /**
  30847. * Disposes the material.
  30848. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  30849. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  30850. */
  30851. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  30852. // Animations
  30853. this.getScene().stopAnimation(this);
  30854. // Remove from scene
  30855. var index = this._scene.materials.indexOf(this);
  30856. if (index >= 0) {
  30857. this._scene.materials.splice(index, 1);
  30858. }
  30859. // Remove from meshes
  30860. for (index = 0; index < this._scene.meshes.length; index++) {
  30861. var mesh = this._scene.meshes[index];
  30862. if (mesh.material === this) {
  30863. mesh.material = null;
  30864. if (mesh.geometry) {
  30865. var geometry = (mesh.geometry);
  30866. if (this.storeEffectOnSubMeshes) {
  30867. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  30868. var subMesh = _a[_i];
  30869. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  30870. if (forceDisposeEffect && subMesh._materialEffect) {
  30871. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  30872. }
  30873. }
  30874. }
  30875. else {
  30876. geometry._releaseVertexArrayObject(this._effect);
  30877. }
  30878. }
  30879. }
  30880. }
  30881. this._uniformBuffer.dispose();
  30882. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  30883. if (forceDisposeEffect && this._effect) {
  30884. if (!this.storeEffectOnSubMeshes) {
  30885. this._scene.getEngine()._releaseEffect(this._effect);
  30886. }
  30887. this._effect = null;
  30888. }
  30889. // Callback
  30890. this.onDisposeObservable.notifyObservers(this);
  30891. this.onDisposeObservable.clear();
  30892. this.onBindObservable.clear();
  30893. this.onUnBindObservable.clear();
  30894. };
  30895. /**
  30896. * Serializes this material.
  30897. * @returns - serialized material object.
  30898. */
  30899. Material.prototype.serialize = function () {
  30900. return BABYLON.SerializationHelper.Serialize(this);
  30901. };
  30902. /**
  30903. * Creates a MultiMaterial from parse MultiMaterial data.
  30904. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  30905. * @param scene - BJS scene.
  30906. * @returns - MultiMaterial.
  30907. */
  30908. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  30909. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  30910. multiMaterial.id = parsedMultiMaterial.id;
  30911. if (BABYLON.Tags) {
  30912. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  30913. }
  30914. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  30915. var subMatId = parsedMultiMaterial.materials[matIndex];
  30916. if (subMatId) {
  30917. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  30918. }
  30919. else {
  30920. multiMaterial.subMaterials.push(null);
  30921. }
  30922. }
  30923. return multiMaterial;
  30924. };
  30925. /**
  30926. * Creates a material from parsed material data.
  30927. * @param parsedMaterial - Parsed material data.
  30928. * @param scene - BJS scene.
  30929. * @param rootUrl - Root URL containing the material information.
  30930. * @returns - Parsed material.
  30931. */
  30932. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  30933. if (!parsedMaterial.customType) {
  30934. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  30935. }
  30936. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  30937. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  30938. if (!BABYLON.LegacyPBRMaterial) {
  30939. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  30940. return;
  30941. }
  30942. }
  30943. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  30944. return materialType.Parse(parsedMaterial, scene, rootUrl);
  30945. ;
  30946. };
  30947. // Triangle views
  30948. Material._TriangleFillMode = 0;
  30949. Material._WireFrameFillMode = 1;
  30950. Material._PointFillMode = 2;
  30951. // Draw modes
  30952. Material._PointListDrawMode = 3;
  30953. Material._LineListDrawMode = 4;
  30954. Material._LineLoopDrawMode = 5;
  30955. Material._LineStripDrawMode = 6;
  30956. Material._TriangleStripDrawMode = 7;
  30957. Material._TriangleFanDrawMode = 8;
  30958. /**
  30959. * Stores the clock-wise side orientation.
  30960. */
  30961. Material._ClockWiseSideOrientation = 0;
  30962. /**
  30963. * Stores the counter clock-wise side orientation.
  30964. */
  30965. Material._CounterClockWiseSideOrientation = 1;
  30966. /**
  30967. * The dirty texture flag value.
  30968. */
  30969. Material._TextureDirtyFlag = 1;
  30970. /**
  30971. * The dirty light flag value.
  30972. */
  30973. Material._LightDirtyFlag = 2;
  30974. /**
  30975. * The dirty fresnel flag value.
  30976. */
  30977. Material._FresnelDirtyFlag = 4;
  30978. /**
  30979. * The dirty attribute flag value.
  30980. */
  30981. Material._AttributesDirtyFlag = 8;
  30982. /**
  30983. * The dirty misc flag value.
  30984. */
  30985. Material._MiscDirtyFlag = 16;
  30986. __decorate([
  30987. BABYLON.serialize()
  30988. ], Material.prototype, "id", void 0);
  30989. __decorate([
  30990. BABYLON.serialize()
  30991. ], Material.prototype, "name", void 0);
  30992. __decorate([
  30993. BABYLON.serialize()
  30994. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  30995. __decorate([
  30996. BABYLON.serialize()
  30997. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  30998. __decorate([
  30999. BABYLON.serialize()
  31000. ], Material.prototype, "state", void 0);
  31001. __decorate([
  31002. BABYLON.serialize("alpha")
  31003. ], Material.prototype, "_alpha", void 0);
  31004. __decorate([
  31005. BABYLON.serialize("backFaceCulling")
  31006. ], Material.prototype, "_backFaceCulling", void 0);
  31007. __decorate([
  31008. BABYLON.serialize()
  31009. ], Material.prototype, "sideOrientation", void 0);
  31010. __decorate([
  31011. BABYLON.serialize("alphaMode")
  31012. ], Material.prototype, "_alphaMode", void 0);
  31013. __decorate([
  31014. BABYLON.serialize()
  31015. ], Material.prototype, "_needDepthPrePass", void 0);
  31016. __decorate([
  31017. BABYLON.serialize()
  31018. ], Material.prototype, "disableDepthWrite", void 0);
  31019. __decorate([
  31020. BABYLON.serialize()
  31021. ], Material.prototype, "forceDepthWrite", void 0);
  31022. __decorate([
  31023. BABYLON.serialize()
  31024. ], Material.prototype, "separateCullingPass", void 0);
  31025. __decorate([
  31026. BABYLON.serialize("fogEnabled")
  31027. ], Material.prototype, "_fogEnabled", void 0);
  31028. __decorate([
  31029. BABYLON.serialize()
  31030. ], Material.prototype, "pointSize", void 0);
  31031. __decorate([
  31032. BABYLON.serialize()
  31033. ], Material.prototype, "zOffset", void 0);
  31034. __decorate([
  31035. BABYLON.serialize()
  31036. ], Material.prototype, "wireframe", null);
  31037. __decorate([
  31038. BABYLON.serialize()
  31039. ], Material.prototype, "pointsCloud", null);
  31040. __decorate([
  31041. BABYLON.serialize()
  31042. ], Material.prototype, "fillMode", null);
  31043. return Material;
  31044. }());
  31045. BABYLON.Material = Material;
  31046. })(BABYLON || (BABYLON = {}));
  31047. //# sourceMappingURL=babylon.material.js.map
  31048. var BABYLON;
  31049. (function (BABYLON) {
  31050. var UniformBuffer = /** @class */ (function () {
  31051. /**
  31052. * Uniform buffer objects.
  31053. *
  31054. * Handles blocks of uniform on the GPU.
  31055. *
  31056. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31057. *
  31058. * For more information, please refer to :
  31059. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31060. */
  31061. function UniformBuffer(engine, data, dynamic) {
  31062. this._engine = engine;
  31063. this._noUBO = !engine.supportsUniformBuffers;
  31064. this._dynamic = dynamic;
  31065. this._data = data || [];
  31066. this._uniformLocations = {};
  31067. this._uniformSizes = {};
  31068. this._uniformLocationPointer = 0;
  31069. this._needSync = false;
  31070. if (this._noUBO) {
  31071. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31072. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31073. this.updateFloat = this._updateFloatForEffect;
  31074. this.updateFloat2 = this._updateFloat2ForEffect;
  31075. this.updateFloat3 = this._updateFloat3ForEffect;
  31076. this.updateFloat4 = this._updateFloat4ForEffect;
  31077. this.updateMatrix = this._updateMatrixForEffect;
  31078. this.updateVector3 = this._updateVector3ForEffect;
  31079. this.updateVector4 = this._updateVector4ForEffect;
  31080. this.updateColor3 = this._updateColor3ForEffect;
  31081. this.updateColor4 = this._updateColor4ForEffect;
  31082. }
  31083. else {
  31084. this._engine._uniformBuffers.push(this);
  31085. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31086. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31087. this.updateFloat = this._updateFloatForUniform;
  31088. this.updateFloat2 = this._updateFloat2ForUniform;
  31089. this.updateFloat3 = this._updateFloat3ForUniform;
  31090. this.updateFloat4 = this._updateFloat4ForUniform;
  31091. this.updateMatrix = this._updateMatrixForUniform;
  31092. this.updateVector3 = this._updateVector3ForUniform;
  31093. this.updateVector4 = this._updateVector4ForUniform;
  31094. this.updateColor3 = this._updateColor3ForUniform;
  31095. this.updateColor4 = this._updateColor4ForUniform;
  31096. }
  31097. }
  31098. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  31099. // Properties
  31100. /**
  31101. * Indicates if the buffer is using the WebGL2 UBO implementation,
  31102. * or just falling back on setUniformXXX calls.
  31103. */
  31104. get: function () {
  31105. return !this._noUBO;
  31106. },
  31107. enumerable: true,
  31108. configurable: true
  31109. });
  31110. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  31111. /**
  31112. * Indicates if the WebGL underlying uniform buffer is in sync
  31113. * with the javascript cache data.
  31114. */
  31115. get: function () {
  31116. return !this._needSync;
  31117. },
  31118. enumerable: true,
  31119. configurable: true
  31120. });
  31121. /**
  31122. * Indicates if the WebGL underlying uniform buffer is dynamic.
  31123. * Also, a dynamic UniformBuffer will disable cache verification and always
  31124. * update the underlying WebGL uniform buffer to the GPU.
  31125. */
  31126. UniformBuffer.prototype.isDynamic = function () {
  31127. return this._dynamic !== undefined;
  31128. };
  31129. /**
  31130. * The data cache on JS side.
  31131. */
  31132. UniformBuffer.prototype.getData = function () {
  31133. return this._bufferData;
  31134. };
  31135. /**
  31136. * The underlying WebGL Uniform buffer.
  31137. */
  31138. UniformBuffer.prototype.getBuffer = function () {
  31139. return this._buffer;
  31140. };
  31141. /**
  31142. * std140 layout specifies how to align data within an UBO structure.
  31143. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  31144. * for specs.
  31145. */
  31146. UniformBuffer.prototype._fillAlignment = function (size) {
  31147. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  31148. // and 4x4 matrices
  31149. // TODO : change if other types are used
  31150. var alignment;
  31151. if (size <= 2) {
  31152. alignment = size;
  31153. }
  31154. else {
  31155. alignment = 4;
  31156. }
  31157. if ((this._uniformLocationPointer % alignment) !== 0) {
  31158. var oldPointer = this._uniformLocationPointer;
  31159. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  31160. var diff = this._uniformLocationPointer - oldPointer;
  31161. for (var i = 0; i < diff; i++) {
  31162. this._data.push(0);
  31163. }
  31164. }
  31165. };
  31166. /**
  31167. * Adds an uniform in the buffer.
  31168. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  31169. * for the layout to be correct !
  31170. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31171. * @param {number|number[]} size Data size, or data directly.
  31172. */
  31173. UniformBuffer.prototype.addUniform = function (name, size) {
  31174. if (this._noUBO) {
  31175. return;
  31176. }
  31177. if (this._uniformLocations[name] !== undefined) {
  31178. // Already existing uniform
  31179. return;
  31180. }
  31181. // This function must be called in the order of the shader layout !
  31182. // size can be the size of the uniform, or data directly
  31183. var data;
  31184. if (size instanceof Array) {
  31185. data = size;
  31186. size = data.length;
  31187. }
  31188. else {
  31189. size = size;
  31190. data = [];
  31191. // Fill with zeros
  31192. for (var i = 0; i < size; i++) {
  31193. data.push(0);
  31194. }
  31195. }
  31196. this._fillAlignment(size);
  31197. this._uniformSizes[name] = size;
  31198. this._uniformLocations[name] = this._uniformLocationPointer;
  31199. this._uniformLocationPointer += size;
  31200. for (var i = 0; i < size; i++) {
  31201. this._data.push(data[i]);
  31202. }
  31203. this._needSync = true;
  31204. };
  31205. /**
  31206. * Wrapper for addUniform.
  31207. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31208. * @param {Matrix} mat A 4x4 matrix.
  31209. */
  31210. UniformBuffer.prototype.addMatrix = function (name, mat) {
  31211. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  31212. };
  31213. /**
  31214. * Wrapper for addUniform.
  31215. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31216. * @param {number} x
  31217. * @param {number} y
  31218. */
  31219. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  31220. var temp = [x, y];
  31221. this.addUniform(name, temp);
  31222. };
  31223. /**
  31224. * Wrapper for addUniform.
  31225. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31226. * @param {number} x
  31227. * @param {number} y
  31228. * @param {number} z
  31229. */
  31230. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  31231. var temp = [x, y, z];
  31232. this.addUniform(name, temp);
  31233. };
  31234. /**
  31235. * Wrapper for addUniform.
  31236. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31237. * @param {Color3} color
  31238. */
  31239. UniformBuffer.prototype.addColor3 = function (name, color) {
  31240. var temp = new Array();
  31241. color.toArray(temp);
  31242. this.addUniform(name, temp);
  31243. };
  31244. /**
  31245. * Wrapper for addUniform.
  31246. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31247. * @param {Color3} color
  31248. * @param {number} alpha
  31249. */
  31250. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  31251. var temp = new Array();
  31252. color.toArray(temp);
  31253. temp.push(alpha);
  31254. this.addUniform(name, temp);
  31255. };
  31256. /**
  31257. * Wrapper for addUniform.
  31258. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31259. * @param {Vector3} vector
  31260. */
  31261. UniformBuffer.prototype.addVector3 = function (name, vector) {
  31262. var temp = new Array();
  31263. vector.toArray(temp);
  31264. this.addUniform(name, temp);
  31265. };
  31266. /**
  31267. * Wrapper for addUniform.
  31268. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31269. */
  31270. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  31271. this.addUniform(name, 12);
  31272. };
  31273. /**
  31274. * Wrapper for addUniform.
  31275. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31276. */
  31277. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  31278. this.addUniform(name, 8);
  31279. };
  31280. /**
  31281. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  31282. */
  31283. UniformBuffer.prototype.create = function () {
  31284. if (this._noUBO) {
  31285. return;
  31286. }
  31287. if (this._buffer) {
  31288. return; // nothing to do
  31289. }
  31290. // See spec, alignment must be filled as a vec4
  31291. this._fillAlignment(4);
  31292. this._bufferData = new Float32Array(this._data);
  31293. this._rebuild();
  31294. this._needSync = true;
  31295. };
  31296. UniformBuffer.prototype._rebuild = function () {
  31297. if (this._noUBO) {
  31298. return;
  31299. }
  31300. if (this._dynamic) {
  31301. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  31302. }
  31303. else {
  31304. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  31305. }
  31306. };
  31307. /**
  31308. * Updates the WebGL Uniform Buffer on the GPU.
  31309. * If the `dynamic` flag is set to true, no cache comparison is done.
  31310. * Otherwise, the buffer will be updated only if the cache differs.
  31311. */
  31312. UniformBuffer.prototype.update = function () {
  31313. if (!this._buffer) {
  31314. this.create();
  31315. return;
  31316. }
  31317. if (!this._dynamic && !this._needSync) {
  31318. return;
  31319. }
  31320. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  31321. this._needSync = false;
  31322. };
  31323. /**
  31324. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  31325. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31326. * @param {number[]|Float32Array} data Flattened data
  31327. * @param {number} size Size of the data.
  31328. */
  31329. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  31330. var location = this._uniformLocations[uniformName];
  31331. if (location === undefined) {
  31332. if (this._buffer) {
  31333. // Cannot add an uniform if the buffer is already created
  31334. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  31335. return;
  31336. }
  31337. this.addUniform(uniformName, size);
  31338. location = this._uniformLocations[uniformName];
  31339. }
  31340. if (!this._buffer) {
  31341. this.create();
  31342. }
  31343. if (!this._dynamic) {
  31344. // Cache for static uniform buffers
  31345. var changed = false;
  31346. for (var i = 0; i < size; i++) {
  31347. if (this._bufferData[location + i] !== data[i]) {
  31348. changed = true;
  31349. this._bufferData[location + i] = data[i];
  31350. }
  31351. }
  31352. this._needSync = this._needSync || changed;
  31353. }
  31354. else {
  31355. // No cache for dynamic
  31356. for (var i = 0; i < size; i++) {
  31357. this._bufferData[location + i] = data[i];
  31358. }
  31359. }
  31360. };
  31361. // Update methods
  31362. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  31363. // To match std140, matrix must be realigned
  31364. for (var i = 0; i < 3; i++) {
  31365. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  31366. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  31367. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  31368. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31369. }
  31370. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  31371. };
  31372. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  31373. this._currentEffect.setMatrix3x3(name, matrix);
  31374. };
  31375. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  31376. this._currentEffect.setMatrix2x2(name, matrix);
  31377. };
  31378. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  31379. // To match std140, matrix must be realigned
  31380. for (var i = 0; i < 2; i++) {
  31381. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  31382. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  31383. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  31384. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31385. }
  31386. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  31387. };
  31388. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  31389. this._currentEffect.setFloat(name, x);
  31390. };
  31391. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  31392. UniformBuffer._tempBuffer[0] = x;
  31393. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  31394. };
  31395. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  31396. if (suffix === void 0) { suffix = ""; }
  31397. this._currentEffect.setFloat2(name + suffix, x, y);
  31398. };
  31399. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  31400. if (suffix === void 0) { suffix = ""; }
  31401. UniformBuffer._tempBuffer[0] = x;
  31402. UniformBuffer._tempBuffer[1] = y;
  31403. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  31404. };
  31405. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  31406. if (suffix === void 0) { suffix = ""; }
  31407. this._currentEffect.setFloat3(name + suffix, x, y, z);
  31408. };
  31409. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  31410. if (suffix === void 0) { suffix = ""; }
  31411. UniformBuffer._tempBuffer[0] = x;
  31412. UniformBuffer._tempBuffer[1] = y;
  31413. UniformBuffer._tempBuffer[2] = z;
  31414. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31415. };
  31416. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  31417. if (suffix === void 0) { suffix = ""; }
  31418. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  31419. };
  31420. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  31421. if (suffix === void 0) { suffix = ""; }
  31422. UniformBuffer._tempBuffer[0] = x;
  31423. UniformBuffer._tempBuffer[1] = y;
  31424. UniformBuffer._tempBuffer[2] = z;
  31425. UniformBuffer._tempBuffer[3] = w;
  31426. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31427. };
  31428. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  31429. this._currentEffect.setMatrix(name, mat);
  31430. };
  31431. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  31432. this.updateUniform(name, mat.toArray(), 16);
  31433. };
  31434. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  31435. this._currentEffect.setVector3(name, vector);
  31436. };
  31437. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  31438. vector.toArray(UniformBuffer._tempBuffer);
  31439. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31440. };
  31441. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  31442. this._currentEffect.setVector4(name, vector);
  31443. };
  31444. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  31445. vector.toArray(UniformBuffer._tempBuffer);
  31446. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31447. };
  31448. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  31449. if (suffix === void 0) { suffix = ""; }
  31450. this._currentEffect.setColor3(name + suffix, color);
  31451. };
  31452. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  31453. if (suffix === void 0) { suffix = ""; }
  31454. color.toArray(UniformBuffer._tempBuffer);
  31455. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31456. };
  31457. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  31458. if (suffix === void 0) { suffix = ""; }
  31459. this._currentEffect.setColor4(name + suffix, color, alpha);
  31460. };
  31461. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  31462. if (suffix === void 0) { suffix = ""; }
  31463. color.toArray(UniformBuffer._tempBuffer);
  31464. UniformBuffer._tempBuffer[3] = alpha;
  31465. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31466. };
  31467. /**
  31468. * Sets a sampler uniform on the effect.
  31469. * @param {string} name Name of the sampler.
  31470. * @param {Texture} texture
  31471. */
  31472. UniformBuffer.prototype.setTexture = function (name, texture) {
  31473. this._currentEffect.setTexture(name, texture);
  31474. };
  31475. /**
  31476. * Directly updates the value of the uniform in the cache AND on the GPU.
  31477. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31478. * @param {number[]|Float32Array} data Flattened data
  31479. */
  31480. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  31481. this.updateUniform(uniformName, data, data.length);
  31482. this.update();
  31483. };
  31484. /**
  31485. * Binds this uniform buffer to an effect.
  31486. * @param {Effect} effect
  31487. * @param {string} name Name of the uniform block in the shader.
  31488. */
  31489. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  31490. this._currentEffect = effect;
  31491. if (this._noUBO || !this._buffer) {
  31492. return;
  31493. }
  31494. effect.bindUniformBuffer(this._buffer, name);
  31495. };
  31496. /**
  31497. * Disposes the uniform buffer.
  31498. */
  31499. UniformBuffer.prototype.dispose = function () {
  31500. if (this._noUBO) {
  31501. return;
  31502. }
  31503. var index = this._engine._uniformBuffers.indexOf(this);
  31504. if (index !== -1) {
  31505. this._engine._uniformBuffers.splice(index, 1);
  31506. }
  31507. if (!this._buffer) {
  31508. return;
  31509. }
  31510. if (this._engine._releaseBuffer(this._buffer)) {
  31511. this._buffer = null;
  31512. }
  31513. };
  31514. // Pool for avoiding memory leaks
  31515. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  31516. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  31517. return UniformBuffer;
  31518. }());
  31519. BABYLON.UniformBuffer = UniformBuffer;
  31520. })(BABYLON || (BABYLON = {}));
  31521. //# sourceMappingURL=babylon.uniformBuffer.js.map
  31522. var BABYLON;
  31523. (function (BABYLON) {
  31524. var VertexData = /** @class */ (function () {
  31525. function VertexData() {
  31526. }
  31527. VertexData.prototype.set = function (data, kind) {
  31528. switch (kind) {
  31529. case BABYLON.VertexBuffer.PositionKind:
  31530. this.positions = data;
  31531. break;
  31532. case BABYLON.VertexBuffer.NormalKind:
  31533. this.normals = data;
  31534. break;
  31535. case BABYLON.VertexBuffer.TangentKind:
  31536. this.tangents = data;
  31537. break;
  31538. case BABYLON.VertexBuffer.UVKind:
  31539. this.uvs = data;
  31540. break;
  31541. case BABYLON.VertexBuffer.UV2Kind:
  31542. this.uvs2 = data;
  31543. break;
  31544. case BABYLON.VertexBuffer.UV3Kind:
  31545. this.uvs3 = data;
  31546. break;
  31547. case BABYLON.VertexBuffer.UV4Kind:
  31548. this.uvs4 = data;
  31549. break;
  31550. case BABYLON.VertexBuffer.UV5Kind:
  31551. this.uvs5 = data;
  31552. break;
  31553. case BABYLON.VertexBuffer.UV6Kind:
  31554. this.uvs6 = data;
  31555. break;
  31556. case BABYLON.VertexBuffer.ColorKind:
  31557. this.colors = data;
  31558. break;
  31559. case BABYLON.VertexBuffer.MatricesIndicesKind:
  31560. this.matricesIndices = data;
  31561. break;
  31562. case BABYLON.VertexBuffer.MatricesWeightsKind:
  31563. this.matricesWeights = data;
  31564. break;
  31565. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  31566. this.matricesIndicesExtra = data;
  31567. break;
  31568. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  31569. this.matricesWeightsExtra = data;
  31570. break;
  31571. }
  31572. };
  31573. /**
  31574. * Associates the vertexData to the passed Mesh.
  31575. * Sets it as updatable or not (default `false`).
  31576. * Returns the VertexData.
  31577. */
  31578. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  31579. this._applyTo(mesh, updatable);
  31580. return this;
  31581. };
  31582. /**
  31583. * Associates the vertexData to the passed Geometry.
  31584. * Sets it as updatable or not (default `false`).
  31585. * Returns the VertexData.
  31586. */
  31587. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  31588. this._applyTo(geometry, updatable);
  31589. return this;
  31590. };
  31591. /**
  31592. * Updates the associated mesh.
  31593. * Returns the VertexData.
  31594. */
  31595. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  31596. this._update(mesh);
  31597. return this;
  31598. };
  31599. /**
  31600. * Updates the associated geometry.
  31601. * Returns the VertexData.
  31602. */
  31603. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  31604. this._update(geometry);
  31605. return this;
  31606. };
  31607. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  31608. if (updatable === void 0) { updatable = false; }
  31609. if (this.positions) {
  31610. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  31611. }
  31612. if (this.normals) {
  31613. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  31614. }
  31615. if (this.tangents) {
  31616. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  31617. }
  31618. if (this.uvs) {
  31619. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  31620. }
  31621. if (this.uvs2) {
  31622. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  31623. }
  31624. if (this.uvs3) {
  31625. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  31626. }
  31627. if (this.uvs4) {
  31628. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  31629. }
  31630. if (this.uvs5) {
  31631. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  31632. }
  31633. if (this.uvs6) {
  31634. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  31635. }
  31636. if (this.colors) {
  31637. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  31638. }
  31639. if (this.matricesIndices) {
  31640. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  31641. }
  31642. if (this.matricesWeights) {
  31643. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  31644. }
  31645. if (this.matricesIndicesExtra) {
  31646. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  31647. }
  31648. if (this.matricesWeightsExtra) {
  31649. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  31650. }
  31651. if (this.indices) {
  31652. meshOrGeometry.setIndices(this.indices, null, updatable);
  31653. }
  31654. return this;
  31655. };
  31656. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  31657. if (this.positions) {
  31658. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  31659. }
  31660. if (this.normals) {
  31661. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  31662. }
  31663. if (this.tangents) {
  31664. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  31665. }
  31666. if (this.uvs) {
  31667. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  31668. }
  31669. if (this.uvs2) {
  31670. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  31671. }
  31672. if (this.uvs3) {
  31673. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  31674. }
  31675. if (this.uvs4) {
  31676. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  31677. }
  31678. if (this.uvs5) {
  31679. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  31680. }
  31681. if (this.uvs6) {
  31682. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  31683. }
  31684. if (this.colors) {
  31685. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  31686. }
  31687. if (this.matricesIndices) {
  31688. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  31689. }
  31690. if (this.matricesWeights) {
  31691. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  31692. }
  31693. if (this.matricesIndicesExtra) {
  31694. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  31695. }
  31696. if (this.matricesWeightsExtra) {
  31697. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  31698. }
  31699. if (this.indices) {
  31700. meshOrGeometry.setIndices(this.indices, null);
  31701. }
  31702. return this;
  31703. };
  31704. /**
  31705. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  31706. * Returns the VertexData.
  31707. */
  31708. VertexData.prototype.transform = function (matrix) {
  31709. var transformed = BABYLON.Vector3.Zero();
  31710. var index;
  31711. if (this.positions) {
  31712. var position = BABYLON.Vector3.Zero();
  31713. for (index = 0; index < this.positions.length; index += 3) {
  31714. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  31715. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  31716. this.positions[index] = transformed.x;
  31717. this.positions[index + 1] = transformed.y;
  31718. this.positions[index + 2] = transformed.z;
  31719. }
  31720. }
  31721. if (this.normals) {
  31722. var normal = BABYLON.Vector3.Zero();
  31723. for (index = 0; index < this.normals.length; index += 3) {
  31724. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  31725. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  31726. this.normals[index] = transformed.x;
  31727. this.normals[index + 1] = transformed.y;
  31728. this.normals[index + 2] = transformed.z;
  31729. }
  31730. }
  31731. if (this.tangents) {
  31732. var tangent = BABYLON.Vector4.Zero();
  31733. var tangentTransformed = BABYLON.Vector4.Zero();
  31734. for (index = 0; index < this.tangents.length; index += 4) {
  31735. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  31736. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  31737. this.tangents[index] = tangentTransformed.x;
  31738. this.tangents[index + 1] = tangentTransformed.y;
  31739. this.tangents[index + 2] = tangentTransformed.z;
  31740. this.tangents[index + 3] = tangentTransformed.w;
  31741. }
  31742. }
  31743. return this;
  31744. };
  31745. /**
  31746. * Merges the passed VertexData into the current one.
  31747. * Returns the modified VertexData.
  31748. */
  31749. VertexData.prototype.merge = function (other, options) {
  31750. options = options || {};
  31751. if (other.indices) {
  31752. if (!this.indices) {
  31753. this.indices = [];
  31754. }
  31755. var offset = this.positions ? this.positions.length / 3 : 0;
  31756. for (var index = 0; index < other.indices.length; index++) {
  31757. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  31758. this.indices.push(other.indices[index] + offset);
  31759. }
  31760. }
  31761. this.positions = this._mergeElement(this.positions, other.positions);
  31762. if (!this.positions) {
  31763. return this;
  31764. }
  31765. var count = this.positions.length / 3;
  31766. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  31767. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  31768. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  31769. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  31770. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  31771. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  31772. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  31773. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  31774. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  31775. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  31776. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  31777. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  31778. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  31779. return this;
  31780. };
  31781. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  31782. if (length === void 0) { length = 0; }
  31783. if (defaultValue === void 0) { defaultValue = 0; }
  31784. if (!other && !source) {
  31785. return null;
  31786. }
  31787. if (!other) {
  31788. var padding = new Float32Array(source.length);
  31789. padding.fill(defaultValue);
  31790. return this._mergeElement(source, padding, length);
  31791. }
  31792. if (!source) {
  31793. if (length === 0 || length === other.length) {
  31794. return other;
  31795. }
  31796. var padding = new Float32Array(length - other.length);
  31797. padding.fill(defaultValue);
  31798. return this._mergeElement(padding, other, length);
  31799. }
  31800. var len = other.length + source.length;
  31801. var isSrcTypedArray = source instanceof Float32Array;
  31802. var isOthTypedArray = other instanceof Float32Array;
  31803. // use non-loop method when the source is Float32Array
  31804. if (isSrcTypedArray) {
  31805. var ret32 = new Float32Array(len);
  31806. ret32.set(source);
  31807. ret32.set(other, source.length);
  31808. return ret32;
  31809. // source is number[], when other is also use concat
  31810. }
  31811. else if (!isOthTypedArray) {
  31812. return source.concat(other);
  31813. // source is a number[], but other is a Float32Array, loop required
  31814. }
  31815. else {
  31816. var ret = source.slice(0); // copy source to a separate array
  31817. for (var i = 0, len = other.length; i < len; i++) {
  31818. ret.push(other[i]);
  31819. }
  31820. return ret;
  31821. }
  31822. };
  31823. /**
  31824. * Serializes the VertexData.
  31825. * Returns a serialized object.
  31826. */
  31827. VertexData.prototype.serialize = function () {
  31828. var serializationObject = this.serialize();
  31829. if (this.positions) {
  31830. serializationObject.positions = this.positions;
  31831. }
  31832. if (this.normals) {
  31833. serializationObject.normals = this.normals;
  31834. }
  31835. if (this.tangents) {
  31836. serializationObject.tangents = this.tangents;
  31837. }
  31838. if (this.uvs) {
  31839. serializationObject.uvs = this.uvs;
  31840. }
  31841. if (this.uvs2) {
  31842. serializationObject.uvs2 = this.uvs2;
  31843. }
  31844. if (this.uvs3) {
  31845. serializationObject.uvs3 = this.uvs3;
  31846. }
  31847. if (this.uvs4) {
  31848. serializationObject.uvs4 = this.uvs4;
  31849. }
  31850. if (this.uvs5) {
  31851. serializationObject.uvs5 = this.uvs5;
  31852. }
  31853. if (this.uvs6) {
  31854. serializationObject.uvs6 = this.uvs6;
  31855. }
  31856. if (this.colors) {
  31857. serializationObject.colors = this.colors;
  31858. }
  31859. if (this.matricesIndices) {
  31860. serializationObject.matricesIndices = this.matricesIndices;
  31861. serializationObject.matricesIndices._isExpanded = true;
  31862. }
  31863. if (this.matricesWeights) {
  31864. serializationObject.matricesWeights = this.matricesWeights;
  31865. }
  31866. if (this.matricesIndicesExtra) {
  31867. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  31868. serializationObject.matricesIndicesExtra._isExpanded = true;
  31869. }
  31870. if (this.matricesWeightsExtra) {
  31871. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  31872. }
  31873. serializationObject.indices = this.indices;
  31874. return serializationObject;
  31875. };
  31876. // Statics
  31877. /**
  31878. * Returns the object VertexData associated to the passed mesh.
  31879. */
  31880. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  31881. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  31882. };
  31883. /**
  31884. * Returns the object VertexData associated to the passed geometry.
  31885. */
  31886. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  31887. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  31888. };
  31889. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  31890. var result = new VertexData();
  31891. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31892. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  31893. }
  31894. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31895. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  31896. }
  31897. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  31898. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  31899. }
  31900. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31901. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  31902. }
  31903. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31904. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  31905. }
  31906. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31907. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  31908. }
  31909. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31910. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  31911. }
  31912. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31913. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  31914. }
  31915. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31916. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  31917. }
  31918. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31919. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  31920. }
  31921. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31922. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  31923. }
  31924. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31925. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  31926. }
  31927. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  31928. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  31929. }
  31930. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  31931. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  31932. }
  31933. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  31934. return result;
  31935. };
  31936. /**
  31937. * Creates the vertexData of the Ribbon.
  31938. */
  31939. VertexData.CreateRibbon = function (options) {
  31940. var pathArray = options.pathArray;
  31941. var closeArray = options.closeArray || false;
  31942. var closePath = options.closePath || false;
  31943. var invertUV = options.invertUV || false;
  31944. var defaultOffset = Math.floor(pathArray[0].length / 2);
  31945. var offset = options.offset || defaultOffset;
  31946. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  31947. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31948. var customUV = options.uvs;
  31949. var customColors = options.colors;
  31950. var positions = [];
  31951. var indices = [];
  31952. var normals = [];
  31953. var uvs = [];
  31954. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  31955. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  31956. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  31957. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  31958. var minlg; // minimal length among all paths from pathArray
  31959. var lg = []; // array of path lengths : nb of vertex per path
  31960. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  31961. var p; // path iterator
  31962. var i; // point iterator
  31963. var j; // point iterator
  31964. // if single path in pathArray
  31965. if (pathArray.length < 2) {
  31966. var ar1 = [];
  31967. var ar2 = [];
  31968. for (i = 0; i < pathArray[0].length - offset; i++) {
  31969. ar1.push(pathArray[0][i]);
  31970. ar2.push(pathArray[0][i + offset]);
  31971. }
  31972. pathArray = [ar1, ar2];
  31973. }
  31974. // positions and horizontal distances (u)
  31975. var idc = 0;
  31976. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  31977. var path;
  31978. var l;
  31979. minlg = pathArray[0].length;
  31980. var vectlg;
  31981. var dist;
  31982. for (p = 0; p < pathArray.length; p++) {
  31983. uTotalDistance[p] = 0;
  31984. us[p] = [0];
  31985. path = pathArray[p];
  31986. l = path.length;
  31987. minlg = (minlg < l) ? minlg : l;
  31988. j = 0;
  31989. while (j < l) {
  31990. positions.push(path[j].x, path[j].y, path[j].z);
  31991. if (j > 0) {
  31992. vectlg = path[j].subtract(path[j - 1]).length();
  31993. dist = vectlg + uTotalDistance[p];
  31994. us[p].push(dist);
  31995. uTotalDistance[p] = dist;
  31996. }
  31997. j++;
  31998. }
  31999. if (closePath) {
  32000. j--;
  32001. positions.push(path[0].x, path[0].y, path[0].z);
  32002. vectlg = path[j].subtract(path[0]).length();
  32003. dist = vectlg + uTotalDistance[p];
  32004. us[p].push(dist);
  32005. uTotalDistance[p] = dist;
  32006. }
  32007. lg[p] = l + closePathCorr;
  32008. idx[p] = idc;
  32009. idc += (l + closePathCorr);
  32010. }
  32011. // vertical distances (v)
  32012. var path1;
  32013. var path2;
  32014. var vertex1 = null;
  32015. var vertex2 = null;
  32016. for (i = 0; i < minlg + closePathCorr; i++) {
  32017. vTotalDistance[i] = 0;
  32018. vs[i] = [0];
  32019. for (p = 0; p < pathArray.length - 1; p++) {
  32020. path1 = pathArray[p];
  32021. path2 = pathArray[p + 1];
  32022. if (i === minlg) {
  32023. vertex1 = path1[0];
  32024. vertex2 = path2[0];
  32025. }
  32026. else {
  32027. vertex1 = path1[i];
  32028. vertex2 = path2[i];
  32029. }
  32030. vectlg = vertex2.subtract(vertex1).length();
  32031. dist = vectlg + vTotalDistance[i];
  32032. vs[i].push(dist);
  32033. vTotalDistance[i] = dist;
  32034. }
  32035. if (closeArray && vertex2 && vertex1) {
  32036. path1 = pathArray[p];
  32037. path2 = pathArray[0];
  32038. if (i === minlg) {
  32039. vertex2 = path2[0];
  32040. }
  32041. vectlg = vertex2.subtract(vertex1).length();
  32042. dist = vectlg + vTotalDistance[i];
  32043. vTotalDistance[i] = dist;
  32044. }
  32045. }
  32046. // uvs
  32047. var u;
  32048. var v;
  32049. if (customUV) {
  32050. for (p = 0; p < customUV.length; p++) {
  32051. uvs.push(customUV[p].x, customUV[p].y);
  32052. }
  32053. }
  32054. else {
  32055. for (p = 0; p < pathArray.length; p++) {
  32056. for (i = 0; i < minlg + closePathCorr; i++) {
  32057. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  32058. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  32059. if (invertUV) {
  32060. uvs.push(v, u);
  32061. }
  32062. else {
  32063. uvs.push(u, v);
  32064. }
  32065. }
  32066. }
  32067. }
  32068. // indices
  32069. p = 0; // path index
  32070. var pi = 0; // positions array index
  32071. var l1 = lg[p] - 1; // path1 length
  32072. var l2 = lg[p + 1] - 1; // path2 length
  32073. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32074. var shft = idx[1] - idx[0]; // shift
  32075. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32076. while (pi <= min && p < path1nb) {
  32077. // 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
  32078. indices.push(pi, pi + shft, pi + 1);
  32079. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32080. pi += 1;
  32081. if (pi === min) {
  32082. p++;
  32083. if (p === lg.length - 1) {
  32084. shft = idx[0] - idx[p];
  32085. l1 = lg[p] - 1;
  32086. l2 = lg[0] - 1;
  32087. }
  32088. else {
  32089. shft = idx[p + 1] - idx[p];
  32090. l1 = lg[p] - 1;
  32091. l2 = lg[p + 1] - 1;
  32092. }
  32093. pi = idx[p];
  32094. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32095. }
  32096. }
  32097. // normals
  32098. VertexData.ComputeNormals(positions, indices, normals);
  32099. if (closePath) {
  32100. var indexFirst = 0;
  32101. var indexLast = 0;
  32102. for (p = 0; p < pathArray.length; p++) {
  32103. indexFirst = idx[p] * 3;
  32104. if (p + 1 < pathArray.length) {
  32105. indexLast = (idx[p + 1] - 1) * 3;
  32106. }
  32107. else {
  32108. indexLast = normals.length - 3;
  32109. }
  32110. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32111. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32112. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32113. normals[indexLast] = normals[indexFirst];
  32114. normals[indexLast + 1] = normals[indexFirst + 1];
  32115. normals[indexLast + 2] = normals[indexFirst + 2];
  32116. }
  32117. }
  32118. // sides
  32119. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32120. // Colors
  32121. var colors = null;
  32122. if (customColors) {
  32123. colors = new Float32Array(customColors.length * 4);
  32124. for (var c = 0; c < customColors.length; c++) {
  32125. colors[c * 4] = customColors[c].r;
  32126. colors[c * 4 + 1] = customColors[c].g;
  32127. colors[c * 4 + 2] = customColors[c].b;
  32128. colors[c * 4 + 3] = customColors[c].a;
  32129. }
  32130. }
  32131. // Result
  32132. var vertexData = new VertexData();
  32133. var positions32 = new Float32Array(positions);
  32134. var normals32 = new Float32Array(normals);
  32135. var uvs32 = new Float32Array(uvs);
  32136. vertexData.indices = indices;
  32137. vertexData.positions = positions32;
  32138. vertexData.normals = normals32;
  32139. vertexData.uvs = uvs32;
  32140. if (colors) {
  32141. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  32142. }
  32143. if (closePath) {
  32144. vertexData._idx = idx;
  32145. }
  32146. return vertexData;
  32147. };
  32148. /**
  32149. * Creates the VertexData of the Box.
  32150. */
  32151. VertexData.CreateBox = function (options) {
  32152. var normalsSource = [
  32153. new BABYLON.Vector3(0, 0, 1),
  32154. new BABYLON.Vector3(0, 0, -1),
  32155. new BABYLON.Vector3(1, 0, 0),
  32156. new BABYLON.Vector3(-1, 0, 0),
  32157. new BABYLON.Vector3(0, 1, 0),
  32158. new BABYLON.Vector3(0, -1, 0)
  32159. ];
  32160. var indices = [];
  32161. var positions = [];
  32162. var normals = [];
  32163. var uvs = [];
  32164. var width = options.width || options.size || 1;
  32165. var height = options.height || options.size || 1;
  32166. var depth = options.depth || options.size || 1;
  32167. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32168. var faceUV = options.faceUV || new Array(6);
  32169. var faceColors = options.faceColors;
  32170. var colors = [];
  32171. // default face colors and UV if undefined
  32172. for (var f = 0; f < 6; f++) {
  32173. if (faceUV[f] === undefined) {
  32174. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32175. }
  32176. if (faceColors && faceColors[f] === undefined) {
  32177. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32178. }
  32179. }
  32180. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32181. // Create each face in turn.
  32182. for (var index = 0; index < normalsSource.length; index++) {
  32183. var normal = normalsSource[index];
  32184. // Get two vectors perpendicular to the face normal and to each other.
  32185. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32186. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32187. // Six indices (two triangles) per face.
  32188. var verticesLength = positions.length / 3;
  32189. indices.push(verticesLength);
  32190. indices.push(verticesLength + 1);
  32191. indices.push(verticesLength + 2);
  32192. indices.push(verticesLength);
  32193. indices.push(verticesLength + 2);
  32194. indices.push(verticesLength + 3);
  32195. // Four vertices per face.
  32196. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32197. positions.push(vertex.x, vertex.y, vertex.z);
  32198. normals.push(normal.x, normal.y, normal.z);
  32199. uvs.push(faceUV[index].z, faceUV[index].w);
  32200. if (faceColors) {
  32201. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32202. }
  32203. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32204. positions.push(vertex.x, vertex.y, vertex.z);
  32205. normals.push(normal.x, normal.y, normal.z);
  32206. uvs.push(faceUV[index].x, faceUV[index].w);
  32207. if (faceColors) {
  32208. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32209. }
  32210. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  32211. positions.push(vertex.x, vertex.y, vertex.z);
  32212. normals.push(normal.x, normal.y, normal.z);
  32213. uvs.push(faceUV[index].x, faceUV[index].y);
  32214. if (faceColors) {
  32215. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32216. }
  32217. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  32218. positions.push(vertex.x, vertex.y, vertex.z);
  32219. normals.push(normal.x, normal.y, normal.z);
  32220. uvs.push(faceUV[index].z, faceUV[index].y);
  32221. if (faceColors) {
  32222. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32223. }
  32224. }
  32225. // sides
  32226. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32227. // Result
  32228. var vertexData = new VertexData();
  32229. vertexData.indices = indices;
  32230. vertexData.positions = positions;
  32231. vertexData.normals = normals;
  32232. vertexData.uvs = uvs;
  32233. if (faceColors) {
  32234. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  32235. vertexData.colors = totalColors;
  32236. }
  32237. return vertexData;
  32238. };
  32239. /**
  32240. * Creates the VertexData of the Sphere.
  32241. */
  32242. VertexData.CreateSphere = function (options) {
  32243. var segments = options.segments || 32;
  32244. var diameterX = options.diameterX || options.diameter || 1;
  32245. var diameterY = options.diameterY || options.diameter || 1;
  32246. var diameterZ = options.diameterZ || options.diameter || 1;
  32247. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32248. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  32249. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32250. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  32251. var totalZRotationSteps = 2 + segments;
  32252. var totalYRotationSteps = 2 * totalZRotationSteps;
  32253. var indices = [];
  32254. var positions = [];
  32255. var normals = [];
  32256. var uvs = [];
  32257. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  32258. var normalizedZ = zRotationStep / totalZRotationSteps;
  32259. var angleZ = normalizedZ * Math.PI * slice;
  32260. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  32261. var normalizedY = yRotationStep / totalYRotationSteps;
  32262. var angleY = normalizedY * Math.PI * 2 * arc;
  32263. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  32264. var rotationY = BABYLON.Matrix.RotationY(angleY);
  32265. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  32266. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  32267. var vertex = complete.multiply(radius);
  32268. var normal = complete.divide(radius).normalize();
  32269. positions.push(vertex.x, vertex.y, vertex.z);
  32270. normals.push(normal.x, normal.y, normal.z);
  32271. uvs.push(normalizedY, normalizedZ);
  32272. }
  32273. if (zRotationStep > 0) {
  32274. var verticesCount = positions.length / 3;
  32275. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  32276. indices.push((firstIndex));
  32277. indices.push((firstIndex + 1));
  32278. indices.push(firstIndex + totalYRotationSteps + 1);
  32279. indices.push((firstIndex + totalYRotationSteps + 1));
  32280. indices.push((firstIndex + 1));
  32281. indices.push((firstIndex + totalYRotationSteps + 2));
  32282. }
  32283. }
  32284. }
  32285. // Sides
  32286. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32287. // Result
  32288. var vertexData = new VertexData();
  32289. vertexData.indices = indices;
  32290. vertexData.positions = positions;
  32291. vertexData.normals = normals;
  32292. vertexData.uvs = uvs;
  32293. return vertexData;
  32294. };
  32295. /**
  32296. * Creates the VertexData of the Cylinder or Cone.
  32297. */
  32298. VertexData.CreateCylinder = function (options) {
  32299. var height = options.height || 2;
  32300. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  32301. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  32302. var tessellation = options.tessellation || 24;
  32303. var subdivisions = options.subdivisions || 1;
  32304. var hasRings = options.hasRings ? true : false;
  32305. var enclose = options.enclose ? true : false;
  32306. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32307. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32308. var faceUV = options.faceUV || new Array(3);
  32309. var faceColors = options.faceColors;
  32310. // default face colors and UV if undefined
  32311. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  32312. var ringNb = (hasRings) ? subdivisions : 1;
  32313. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  32314. var f;
  32315. for (f = 0; f < surfaceNb; f++) {
  32316. if (faceColors && faceColors[f] === undefined) {
  32317. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32318. }
  32319. }
  32320. for (f = 0; f < surfaceNb; f++) {
  32321. if (faceUV && faceUV[f] === undefined) {
  32322. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32323. }
  32324. }
  32325. var indices = new Array();
  32326. var positions = new Array();
  32327. var normals = new Array();
  32328. var uvs = new Array();
  32329. var colors = new Array();
  32330. var angle_step = Math.PI * 2 * arc / tessellation;
  32331. var angle;
  32332. var h;
  32333. var radius;
  32334. var tan = (diameterBottom - diameterTop) / 2 / height;
  32335. var ringVertex = BABYLON.Vector3.Zero();
  32336. var ringNormal = BABYLON.Vector3.Zero();
  32337. var ringFirstVertex = BABYLON.Vector3.Zero();
  32338. var ringFirstNormal = BABYLON.Vector3.Zero();
  32339. var quadNormal = BABYLON.Vector3.Zero();
  32340. var Y = BABYLON.Axis.Y;
  32341. // positions, normals, uvs
  32342. var i;
  32343. var j;
  32344. var r;
  32345. var ringIdx = 1;
  32346. var s = 1; // surface index
  32347. var cs = 0;
  32348. var v = 0;
  32349. for (i = 0; i <= subdivisions; i++) {
  32350. h = i / subdivisions;
  32351. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  32352. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  32353. for (r = 0; r < ringIdx; r++) {
  32354. if (hasRings) {
  32355. s += r;
  32356. }
  32357. if (enclose) {
  32358. s += 2 * r;
  32359. }
  32360. for (j = 0; j <= tessellation; j++) {
  32361. angle = j * angle_step;
  32362. // position
  32363. ringVertex.x = Math.cos(-angle) * radius;
  32364. ringVertex.y = -height / 2 + h * height;
  32365. ringVertex.z = Math.sin(-angle) * radius;
  32366. // normal
  32367. if (diameterTop === 0 && i === subdivisions) {
  32368. // if no top cap, reuse former normals
  32369. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  32370. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  32371. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  32372. }
  32373. else {
  32374. ringNormal.x = ringVertex.x;
  32375. ringNormal.z = ringVertex.z;
  32376. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  32377. ringNormal.normalize();
  32378. }
  32379. // keep first ring vertex values for enclose
  32380. if (j === 0) {
  32381. ringFirstVertex.copyFrom(ringVertex);
  32382. ringFirstNormal.copyFrom(ringNormal);
  32383. }
  32384. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32385. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  32386. if (hasRings) {
  32387. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  32388. }
  32389. else {
  32390. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  32391. }
  32392. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  32393. if (faceColors) {
  32394. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  32395. }
  32396. }
  32397. // if enclose, add four vertices and their dedicated normals
  32398. if (arc !== 1 && enclose) {
  32399. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32400. positions.push(0, ringVertex.y, 0);
  32401. positions.push(0, ringVertex.y, 0);
  32402. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  32403. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  32404. quadNormal.normalize();
  32405. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32406. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  32407. quadNormal.normalize();
  32408. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32409. if (hasRings) {
  32410. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  32411. }
  32412. else {
  32413. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  32414. }
  32415. uvs.push(faceUV[s + 1].x, v);
  32416. uvs.push(faceUV[s + 1].z, v);
  32417. if (hasRings) {
  32418. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  32419. }
  32420. else {
  32421. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  32422. }
  32423. uvs.push(faceUV[s + 2].x, v);
  32424. uvs.push(faceUV[s + 2].z, v);
  32425. if (faceColors) {
  32426. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32427. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32428. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32429. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32430. }
  32431. }
  32432. if (cs !== s) {
  32433. cs = s;
  32434. }
  32435. }
  32436. }
  32437. // indices
  32438. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  32439. var s;
  32440. i = 0;
  32441. for (s = 0; s < subdivisions; s++) {
  32442. var i0 = 0;
  32443. var i1 = 0;
  32444. var i2 = 0;
  32445. var i3 = 0;
  32446. for (j = 0; j < tessellation; j++) {
  32447. i0 = i * (e + 1) + j;
  32448. i1 = (i + 1) * (e + 1) + j;
  32449. i2 = i * (e + 1) + (j + 1);
  32450. i3 = (i + 1) * (e + 1) + (j + 1);
  32451. indices.push(i0, i1, i2);
  32452. indices.push(i3, i2, i1);
  32453. }
  32454. if (arc !== 1 && enclose) {
  32455. indices.push(i0 + 2, i1 + 2, i2 + 2);
  32456. indices.push(i3 + 2, i2 + 2, i1 + 2);
  32457. indices.push(i0 + 4, i1 + 4, i2 + 4);
  32458. indices.push(i3 + 4, i2 + 4, i1 + 4);
  32459. }
  32460. i = (hasRings) ? (i + 2) : (i + 1);
  32461. }
  32462. // Caps
  32463. var createCylinderCap = function (isTop) {
  32464. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  32465. if (radius === 0) {
  32466. return;
  32467. }
  32468. // Cap positions, normals & uvs
  32469. var angle;
  32470. var circleVector;
  32471. var i;
  32472. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  32473. var c = null;
  32474. if (faceColors) {
  32475. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  32476. }
  32477. // cap center
  32478. var vbase = positions.length / 3;
  32479. var offset = isTop ? height / 2 : -height / 2;
  32480. var center = new BABYLON.Vector3(0, offset, 0);
  32481. positions.push(center.x, center.y, center.z);
  32482. normals.push(0, isTop ? 1 : -1, 0);
  32483. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  32484. if (c) {
  32485. colors.push(c.r, c.g, c.b, c.a);
  32486. }
  32487. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  32488. for (i = 0; i <= tessellation; i++) {
  32489. angle = Math.PI * 2 * i * arc / tessellation;
  32490. var cos = Math.cos(-angle);
  32491. var sin = Math.sin(-angle);
  32492. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  32493. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  32494. positions.push(circleVector.x, circleVector.y, circleVector.z);
  32495. normals.push(0, isTop ? 1 : -1, 0);
  32496. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  32497. if (c) {
  32498. colors.push(c.r, c.g, c.b, c.a);
  32499. }
  32500. }
  32501. // Cap indices
  32502. for (i = 0; i < tessellation; i++) {
  32503. if (!isTop) {
  32504. indices.push(vbase);
  32505. indices.push(vbase + (i + 1));
  32506. indices.push(vbase + (i + 2));
  32507. }
  32508. else {
  32509. indices.push(vbase);
  32510. indices.push(vbase + (i + 2));
  32511. indices.push(vbase + (i + 1));
  32512. }
  32513. }
  32514. };
  32515. // add caps to geometry
  32516. createCylinderCap(false);
  32517. createCylinderCap(true);
  32518. // Sides
  32519. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32520. var vertexData = new VertexData();
  32521. vertexData.indices = indices;
  32522. vertexData.positions = positions;
  32523. vertexData.normals = normals;
  32524. vertexData.uvs = uvs;
  32525. if (faceColors) {
  32526. vertexData.colors = colors;
  32527. }
  32528. return vertexData;
  32529. };
  32530. /**
  32531. * Creates the VertexData of the Torus.
  32532. */
  32533. VertexData.CreateTorus = function (options) {
  32534. var indices = [];
  32535. var positions = [];
  32536. var normals = [];
  32537. var uvs = [];
  32538. var diameter = options.diameter || 1;
  32539. var thickness = options.thickness || 0.5;
  32540. var tessellation = options.tessellation || 16;
  32541. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32542. var stride = tessellation + 1;
  32543. for (var i = 0; i <= tessellation; i++) {
  32544. var u = i / tessellation;
  32545. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  32546. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  32547. for (var j = 0; j <= tessellation; j++) {
  32548. var v = 1 - j / tessellation;
  32549. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  32550. var dx = Math.cos(innerAngle);
  32551. var dy = Math.sin(innerAngle);
  32552. // Create a vertex.
  32553. var normal = new BABYLON.Vector3(dx, dy, 0);
  32554. var position = normal.scale(thickness / 2);
  32555. var textureCoordinate = new BABYLON.Vector2(u, v);
  32556. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  32557. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  32558. positions.push(position.x, position.y, position.z);
  32559. normals.push(normal.x, normal.y, normal.z);
  32560. uvs.push(textureCoordinate.x, textureCoordinate.y);
  32561. // And create indices for two triangles.
  32562. var nextI = (i + 1) % stride;
  32563. var nextJ = (j + 1) % stride;
  32564. indices.push(i * stride + j);
  32565. indices.push(i * stride + nextJ);
  32566. indices.push(nextI * stride + j);
  32567. indices.push(i * stride + nextJ);
  32568. indices.push(nextI * stride + nextJ);
  32569. indices.push(nextI * stride + j);
  32570. }
  32571. }
  32572. // Sides
  32573. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32574. // Result
  32575. var vertexData = new VertexData();
  32576. vertexData.indices = indices;
  32577. vertexData.positions = positions;
  32578. vertexData.normals = normals;
  32579. vertexData.uvs = uvs;
  32580. return vertexData;
  32581. };
  32582. /**
  32583. * Creates the VertexData of the LineSystem.
  32584. */
  32585. VertexData.CreateLineSystem = function (options) {
  32586. var indices = [];
  32587. var positions = [];
  32588. var lines = options.lines;
  32589. var colors = options.colors;
  32590. var vertexColors = [];
  32591. var idx = 0;
  32592. for (var l = 0; l < lines.length; l++) {
  32593. var points = lines[l];
  32594. for (var index = 0; index < points.length; index++) {
  32595. positions.push(points[index].x, points[index].y, points[index].z);
  32596. if (colors) {
  32597. var color = colors[l];
  32598. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  32599. }
  32600. if (index > 0) {
  32601. indices.push(idx - 1);
  32602. indices.push(idx);
  32603. }
  32604. idx++;
  32605. }
  32606. }
  32607. var vertexData = new VertexData();
  32608. vertexData.indices = indices;
  32609. vertexData.positions = positions;
  32610. if (colors) {
  32611. vertexData.colors = vertexColors;
  32612. }
  32613. return vertexData;
  32614. };
  32615. /**
  32616. * Create the VertexData of the DashedLines.
  32617. */
  32618. VertexData.CreateDashedLines = function (options) {
  32619. var dashSize = options.dashSize || 3;
  32620. var gapSize = options.gapSize || 1;
  32621. var dashNb = options.dashNb || 200;
  32622. var points = options.points;
  32623. var positions = new Array();
  32624. var indices = new Array();
  32625. var curvect = BABYLON.Vector3.Zero();
  32626. var lg = 0;
  32627. var nb = 0;
  32628. var shft = 0;
  32629. var dashshft = 0;
  32630. var curshft = 0;
  32631. var idx = 0;
  32632. var i = 0;
  32633. for (i = 0; i < points.length - 1; i++) {
  32634. points[i + 1].subtractToRef(points[i], curvect);
  32635. lg += curvect.length();
  32636. }
  32637. shft = lg / dashNb;
  32638. dashshft = dashSize * shft / (dashSize + gapSize);
  32639. for (i = 0; i < points.length - 1; i++) {
  32640. points[i + 1].subtractToRef(points[i], curvect);
  32641. nb = Math.floor(curvect.length() / shft);
  32642. curvect.normalize();
  32643. for (var j = 0; j < nb; j++) {
  32644. curshft = shft * j;
  32645. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  32646. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  32647. indices.push(idx, idx + 1);
  32648. idx += 2;
  32649. }
  32650. }
  32651. // Result
  32652. var vertexData = new VertexData();
  32653. vertexData.positions = positions;
  32654. vertexData.indices = indices;
  32655. return vertexData;
  32656. };
  32657. /**
  32658. * Creates the VertexData of the Ground.
  32659. */
  32660. VertexData.CreateGround = function (options) {
  32661. var indices = [];
  32662. var positions = [];
  32663. var normals = [];
  32664. var uvs = [];
  32665. var row, col;
  32666. var width = options.width || 1;
  32667. var height = options.height || 1;
  32668. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  32669. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  32670. for (row = 0; row <= subdivisionsY; row++) {
  32671. for (col = 0; col <= subdivisionsX; col++) {
  32672. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  32673. var normal = new BABYLON.Vector3(0, 1.0, 0);
  32674. positions.push(position.x, position.y, position.z);
  32675. normals.push(normal.x, normal.y, normal.z);
  32676. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  32677. }
  32678. }
  32679. for (row = 0; row < subdivisionsY; row++) {
  32680. for (col = 0; col < subdivisionsX; col++) {
  32681. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  32682. indices.push(col + 1 + row * (subdivisionsX + 1));
  32683. indices.push(col + row * (subdivisionsX + 1));
  32684. indices.push(col + (row + 1) * (subdivisionsX + 1));
  32685. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  32686. indices.push(col + row * (subdivisionsX + 1));
  32687. }
  32688. }
  32689. // Result
  32690. var vertexData = new VertexData();
  32691. vertexData.indices = indices;
  32692. vertexData.positions = positions;
  32693. vertexData.normals = normals;
  32694. vertexData.uvs = uvs;
  32695. return vertexData;
  32696. };
  32697. /**
  32698. * Creates the VertexData of the TiledGround.
  32699. */
  32700. VertexData.CreateTiledGround = function (options) {
  32701. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  32702. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  32703. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  32704. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  32705. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  32706. var precision = options.precision || { w: 1, h: 1 };
  32707. var indices = new Array();
  32708. var positions = new Array();
  32709. var normals = new Array();
  32710. var uvs = new Array();
  32711. var row, col, tileRow, tileCol;
  32712. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  32713. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  32714. precision.w = (precision.w < 1) ? 1 : precision.w;
  32715. precision.h = (precision.h < 1) ? 1 : precision.h;
  32716. var tileSize = {
  32717. 'w': (xmax - xmin) / subdivisions.w,
  32718. 'h': (zmax - zmin) / subdivisions.h
  32719. };
  32720. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  32721. // Indices
  32722. var base = positions.length / 3;
  32723. var rowLength = precision.w + 1;
  32724. for (row = 0; row < precision.h; row++) {
  32725. for (col = 0; col < precision.w; col++) {
  32726. var square = [
  32727. base + col + row * rowLength,
  32728. base + (col + 1) + row * rowLength,
  32729. base + (col + 1) + (row + 1) * rowLength,
  32730. base + col + (row + 1) * rowLength
  32731. ];
  32732. indices.push(square[1]);
  32733. indices.push(square[2]);
  32734. indices.push(square[3]);
  32735. indices.push(square[0]);
  32736. indices.push(square[1]);
  32737. indices.push(square[3]);
  32738. }
  32739. }
  32740. // Position, normals and uvs
  32741. var position = BABYLON.Vector3.Zero();
  32742. var normal = new BABYLON.Vector3(0, 1.0, 0);
  32743. for (row = 0; row <= precision.h; row++) {
  32744. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  32745. for (col = 0; col <= precision.w; col++) {
  32746. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  32747. position.y = 0;
  32748. positions.push(position.x, position.y, position.z);
  32749. normals.push(normal.x, normal.y, normal.z);
  32750. uvs.push(col / precision.w, row / precision.h);
  32751. }
  32752. }
  32753. }
  32754. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  32755. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  32756. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  32757. }
  32758. }
  32759. // Result
  32760. var vertexData = new VertexData();
  32761. vertexData.indices = indices;
  32762. vertexData.positions = positions;
  32763. vertexData.normals = normals;
  32764. vertexData.uvs = uvs;
  32765. return vertexData;
  32766. };
  32767. /**
  32768. * Creates the VertexData of the Ground designed from a heightmap.
  32769. */
  32770. VertexData.CreateGroundFromHeightMap = function (options) {
  32771. var indices = [];
  32772. var positions = [];
  32773. var normals = [];
  32774. var uvs = [];
  32775. var row, col;
  32776. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  32777. // Vertices
  32778. for (row = 0; row <= options.subdivisions; row++) {
  32779. for (col = 0; col <= options.subdivisions; col++) {
  32780. 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));
  32781. // Compute height
  32782. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  32783. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  32784. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  32785. var r = options.buffer[pos] / 255.0;
  32786. var g = options.buffer[pos + 1] / 255.0;
  32787. var b = options.buffer[pos + 2] / 255.0;
  32788. var gradient = r * filter.r + g * filter.g + b * filter.b;
  32789. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  32790. // Add vertex
  32791. positions.push(position.x, position.y, position.z);
  32792. normals.push(0, 0, 0);
  32793. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  32794. }
  32795. }
  32796. // Indices
  32797. for (row = 0; row < options.subdivisions; row++) {
  32798. for (col = 0; col < options.subdivisions; col++) {
  32799. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  32800. indices.push(col + 1 + row * (options.subdivisions + 1));
  32801. indices.push(col + row * (options.subdivisions + 1));
  32802. indices.push(col + (row + 1) * (options.subdivisions + 1));
  32803. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  32804. indices.push(col + row * (options.subdivisions + 1));
  32805. }
  32806. }
  32807. // Normals
  32808. VertexData.ComputeNormals(positions, indices, normals);
  32809. // Result
  32810. var vertexData = new VertexData();
  32811. vertexData.indices = indices;
  32812. vertexData.positions = positions;
  32813. vertexData.normals = normals;
  32814. vertexData.uvs = uvs;
  32815. return vertexData;
  32816. };
  32817. /**
  32818. * Creates the VertexData of the Plane.
  32819. */
  32820. VertexData.CreatePlane = function (options) {
  32821. var indices = [];
  32822. var positions = [];
  32823. var normals = [];
  32824. var uvs = [];
  32825. var width = options.width || options.size || 1;
  32826. var height = options.height || options.size || 1;
  32827. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32828. // Vertices
  32829. var halfWidth = width / 2.0;
  32830. var halfHeight = height / 2.0;
  32831. positions.push(-halfWidth, -halfHeight, 0);
  32832. normals.push(0, 0, -1.0);
  32833. uvs.push(0.0, 0.0);
  32834. positions.push(halfWidth, -halfHeight, 0);
  32835. normals.push(0, 0, -1.0);
  32836. uvs.push(1.0, 0.0);
  32837. positions.push(halfWidth, halfHeight, 0);
  32838. normals.push(0, 0, -1.0);
  32839. uvs.push(1.0, 1.0);
  32840. positions.push(-halfWidth, halfHeight, 0);
  32841. normals.push(0, 0, -1.0);
  32842. uvs.push(0.0, 1.0);
  32843. // Indices
  32844. indices.push(0);
  32845. indices.push(1);
  32846. indices.push(2);
  32847. indices.push(0);
  32848. indices.push(2);
  32849. indices.push(3);
  32850. // Sides
  32851. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32852. // Result
  32853. var vertexData = new VertexData();
  32854. vertexData.indices = indices;
  32855. vertexData.positions = positions;
  32856. vertexData.normals = normals;
  32857. vertexData.uvs = uvs;
  32858. return vertexData;
  32859. };
  32860. /**
  32861. * Creates the VertexData of the Disc or regular Polygon.
  32862. */
  32863. VertexData.CreateDisc = function (options) {
  32864. var positions = new Array();
  32865. var indices = new Array();
  32866. var normals = new Array();
  32867. var uvs = new Array();
  32868. var radius = options.radius || 0.5;
  32869. var tessellation = options.tessellation || 64;
  32870. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32871. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32872. // positions and uvs
  32873. positions.push(0, 0, 0); // disc center first
  32874. uvs.push(0.5, 0.5);
  32875. var theta = Math.PI * 2 * arc;
  32876. var step = theta / tessellation;
  32877. for (var a = 0; a < theta; a += step) {
  32878. var x = Math.cos(a);
  32879. var y = Math.sin(a);
  32880. var u = (x + 1) / 2;
  32881. var v = (1 - y) / 2;
  32882. positions.push(radius * x, radius * y, 0);
  32883. uvs.push(u, v);
  32884. }
  32885. if (arc === 1) {
  32886. positions.push(positions[3], positions[4], positions[5]); // close the circle
  32887. uvs.push(uvs[2], uvs[3]);
  32888. }
  32889. //indices
  32890. var vertexNb = positions.length / 3;
  32891. for (var i = 1; i < vertexNb - 1; i++) {
  32892. indices.push(i + 1, 0, i);
  32893. }
  32894. // result
  32895. VertexData.ComputeNormals(positions, indices, normals);
  32896. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32897. var vertexData = new VertexData();
  32898. vertexData.indices = indices;
  32899. vertexData.positions = positions;
  32900. vertexData.normals = normals;
  32901. vertexData.uvs = uvs;
  32902. return vertexData;
  32903. };
  32904. /**
  32905. * Re-creates the VertexData of the Polygon for sideOrientation.
  32906. */
  32907. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  32908. var faceUV = fUV || new Array(3);
  32909. var faceColors = fColors;
  32910. var colors = [];
  32911. // default face colors and UV if undefined
  32912. for (var f = 0; f < 3; f++) {
  32913. if (faceUV[f] === undefined) {
  32914. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32915. }
  32916. if (faceColors && faceColors[f] === undefined) {
  32917. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32918. }
  32919. }
  32920. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32921. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32922. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32923. var indices = polygon.getIndices();
  32924. // set face colours and textures
  32925. var idx = 0;
  32926. var face = 0;
  32927. for (var index = 0; index < normals.length; index += 3) {
  32928. //Edge Face no. 1
  32929. if (Math.abs(normals[index + 1]) < 0.001) {
  32930. face = 1;
  32931. }
  32932. //Top Face no. 0
  32933. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  32934. face = 0;
  32935. }
  32936. //Bottom Face no. 2
  32937. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  32938. face = 2;
  32939. }
  32940. idx = index / 3;
  32941. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  32942. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  32943. if (faceColors) {
  32944. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  32945. }
  32946. }
  32947. // sides
  32948. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  32949. // Result
  32950. var vertexData = new VertexData();
  32951. vertexData.indices = indices;
  32952. vertexData.positions = positions;
  32953. vertexData.normals = normals;
  32954. vertexData.uvs = uvs;
  32955. if (faceColors) {
  32956. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  32957. vertexData.colors = totalColors;
  32958. }
  32959. return vertexData;
  32960. };
  32961. /**
  32962. * Creates the VertexData of the IcoSphere.
  32963. */
  32964. VertexData.CreateIcoSphere = function (options) {
  32965. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32966. var radius = options.radius || 1;
  32967. var flat = (options.flat === undefined) ? true : options.flat;
  32968. var subdivisions = options.subdivisions || 4;
  32969. var radiusX = options.radiusX || radius;
  32970. var radiusY = options.radiusY || radius;
  32971. var radiusZ = options.radiusZ || radius;
  32972. var t = (1 + Math.sqrt(5)) / 2;
  32973. // 12 vertex x,y,z
  32974. var ico_vertices = [
  32975. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  32976. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  32977. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  32978. ];
  32979. // index of 3 vertex makes a face of icopshere
  32980. var ico_indices = [
  32981. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  32982. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  32983. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  32984. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  32985. ];
  32986. // vertex for uv have aliased position, not for UV
  32987. var vertices_unalias_id = [
  32988. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  32989. // vertex alias
  32990. 0,
  32991. 2,
  32992. 3,
  32993. 3,
  32994. 3,
  32995. 4,
  32996. 7,
  32997. 8,
  32998. 9,
  32999. 9,
  33000. 10,
  33001. 11 // 23: B + 12
  33002. ];
  33003. // uv as integer step (not pixels !)
  33004. var ico_vertexuv = [
  33005. 5, 1, 3, 1, 6, 4, 0, 0,
  33006. 5, 3, 4, 2, 2, 2, 4, 0,
  33007. 2, 0, 1, 1, 6, 0, 6, 2,
  33008. // vertex alias (for same vertex on different faces)
  33009. 0, 4,
  33010. 3, 3,
  33011. 4, 4,
  33012. 3, 1,
  33013. 4, 2,
  33014. 4, 4,
  33015. 0, 2,
  33016. 1, 1,
  33017. 2, 2,
  33018. 3, 3,
  33019. 1, 3,
  33020. 2, 4 // 23: B + 12
  33021. ];
  33022. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33023. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33024. // First island of uv mapping
  33025. // v = 4h 3+ 2
  33026. // v = 3h 9+ 4
  33027. // v = 2h 9+ 5 B
  33028. // v = 1h 9 1 0
  33029. // v = 0h 3 8 7 A
  33030. // u = 0 1 2 3 4 5 6 *a
  33031. // Second island of uv mapping
  33032. // v = 4h 0+ B+ 4+
  33033. // v = 3h A+ 2+
  33034. // v = 2h 7+ 6 3+
  33035. // v = 1h 8+ 3+
  33036. // v = 0h
  33037. // u = 0 1 2 3 4 5 6 *a
  33038. // Face layout on texture UV mapping
  33039. // ============
  33040. // \ 4 /\ 16 / ======
  33041. // \ / \ / /\ 11 /
  33042. // \/ 7 \/ / \ /
  33043. // ======= / 10 \/
  33044. // /\ 17 /\ =======
  33045. // / \ / \ \ 15 /\
  33046. // / 8 \/ 12 \ \ / \
  33047. // ============ \/ 6 \
  33048. // \ 18 /\ ============
  33049. // \ / \ \ 5 /\ 0 /
  33050. // \/ 13 \ \ / \ /
  33051. // ======= \/ 1 \/
  33052. // =============
  33053. // /\ 19 /\ 2 /\
  33054. // / \ / \ / \
  33055. // / 14 \/ 9 \/ 3 \
  33056. // ===================
  33057. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33058. var ustep = 138 / 1024;
  33059. var vstep = 239 / 1024;
  33060. var uoffset = 60 / 1024;
  33061. var voffset = 26 / 1024;
  33062. // Second island should have margin, not to touch the first island
  33063. // avoid any borderline artefact in pixel rounding
  33064. var island_u_offset = -40 / 1024;
  33065. var island_v_offset = +20 / 1024;
  33066. // face is either island 0 or 1 :
  33067. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33068. var island = [
  33069. 0, 0, 0, 0, 1,
  33070. 0, 0, 1, 1, 0,
  33071. 0, 0, 1, 1, 0,
  33072. 0, 1, 1, 1, 0 // 15 - 19
  33073. ];
  33074. var indices = new Array();
  33075. var positions = new Array();
  33076. var normals = new Array();
  33077. var uvs = new Array();
  33078. var current_indice = 0;
  33079. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33080. var face_vertex_pos = new Array(3);
  33081. var face_vertex_uv = new Array(3);
  33082. var v012;
  33083. for (v012 = 0; v012 < 3; v012++) {
  33084. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33085. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33086. }
  33087. // create all with normals
  33088. for (var face = 0; face < 20; face++) {
  33089. // 3 vertex per face
  33090. for (v012 = 0; v012 < 3; v012++) {
  33091. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33092. var v_id = ico_indices[3 * face + v012];
  33093. // vertex have 3D position (x,y,z)
  33094. 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]);
  33095. // Normalize to get normal, then scale to radius
  33096. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33097. // uv Coordinates from vertex ID
  33098. 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);
  33099. }
  33100. // Subdivide the face (interpolate pos, norm, uv)
  33101. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33102. // - norm is linear interpolation of vertex corner normal
  33103. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33104. // - uv is linear interpolation
  33105. //
  33106. // Topology is as below for sub-divide by 2
  33107. // vertex shown as v0,v1,v2
  33108. // interp index is i1 to progress in range [v0,v1[
  33109. // interp index is i2 to progress in range [v0,v2[
  33110. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33111. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33112. //
  33113. //
  33114. // i2 v2
  33115. // ^ ^
  33116. // / / \
  33117. // / / \
  33118. // / / \
  33119. // / / (0,1) \
  33120. // / #---------\
  33121. // / / \ (0,0)'/ \
  33122. // / / \ / \
  33123. // / / \ / \
  33124. // / / (0,0) \ / (1,0) \
  33125. // / #---------#---------\
  33126. // v0 v1
  33127. //
  33128. // --------------------> i1
  33129. //
  33130. // interp of (i1,i2):
  33131. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33132. // along i1 : lerp(x0,x1, i1/(S-i2))
  33133. //
  33134. // centroid of triangle is needed to get help normal computation
  33135. // (c1,c2) are used for centroid location
  33136. var interp_vertex = function (i1, i2, c1, c2) {
  33137. // vertex is interpolated from
  33138. // - face_vertex_pos[0..2]
  33139. // - face_vertex_uv[0..2]
  33140. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33141. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33142. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33143. pos_interp.normalize();
  33144. var vertex_normal;
  33145. if (flat) {
  33146. // in flat mode, recalculate normal as face centroid normal
  33147. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33148. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33149. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33150. }
  33151. else {
  33152. // in smooth mode, recalculate normal from each single vertex position
  33153. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33154. }
  33155. // Vertex normal need correction due to X,Y,Z radius scaling
  33156. vertex_normal.x /= radiusX;
  33157. vertex_normal.y /= radiusY;
  33158. vertex_normal.z /= radiusZ;
  33159. vertex_normal.normalize();
  33160. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33161. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33162. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33163. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33164. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33165. uvs.push(uv_interp.x, uv_interp.y);
  33166. // push each vertex has member of a face
  33167. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33168. indices.push(current_indice);
  33169. current_indice++;
  33170. };
  33171. for (var i2 = 0; i2 < subdivisions; i2++) {
  33172. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33173. // face : (i1,i2) for /\ :
  33174. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33175. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33176. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33177. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33178. if (i1 + i2 + 1 < subdivisions) {
  33179. // face : (i1,i2)' for \/ :
  33180. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33181. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33182. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33183. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33184. }
  33185. }
  33186. }
  33187. }
  33188. // Sides
  33189. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33190. // Result
  33191. var vertexData = new VertexData();
  33192. vertexData.indices = indices;
  33193. vertexData.positions = positions;
  33194. vertexData.normals = normals;
  33195. vertexData.uvs = uvs;
  33196. return vertexData;
  33197. };
  33198. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33199. /**
  33200. * Creates the VertexData of the Polyhedron.
  33201. */
  33202. VertexData.CreatePolyhedron = function (options) {
  33203. // provided polyhedron types :
  33204. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33205. // 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)
  33206. var polyhedra = [];
  33207. 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]] };
  33208. 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]] };
  33209. polyhedra[2] = {
  33210. 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]],
  33211. 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]]
  33212. };
  33213. polyhedra[3] = {
  33214. 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]],
  33215. 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]]
  33216. };
  33217. polyhedra[4] = {
  33218. 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]],
  33219. 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]]
  33220. };
  33221. 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]] };
  33222. 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]] };
  33223. 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]] };
  33224. 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]] };
  33225. 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]] };
  33226. 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]] };
  33227. 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]] };
  33228. 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]] };
  33229. 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]] };
  33230. polyhedra[14] = {
  33231. 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]],
  33232. 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]]
  33233. };
  33234. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  33235. var size = options.size;
  33236. var sizeX = options.sizeX || size || 1;
  33237. var sizeY = options.sizeY || size || 1;
  33238. var sizeZ = options.sizeZ || size || 1;
  33239. var data = options.custom || polyhedra[type];
  33240. var nbfaces = data.face.length;
  33241. var faceUV = options.faceUV || new Array(nbfaces);
  33242. var faceColors = options.faceColors;
  33243. var flat = (options.flat === undefined) ? true : options.flat;
  33244. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33245. var positions = new Array();
  33246. var indices = new Array();
  33247. var normals = new Array();
  33248. var uvs = new Array();
  33249. var colors = new Array();
  33250. var index = 0;
  33251. var faceIdx = 0; // face cursor in the array "indexes"
  33252. var indexes = new Array();
  33253. var i = 0;
  33254. var f = 0;
  33255. var u, v, ang, x, y, tmp;
  33256. // default face colors and UV if undefined
  33257. if (flat) {
  33258. for (f = 0; f < nbfaces; f++) {
  33259. if (faceColors && faceColors[f] === undefined) {
  33260. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33261. }
  33262. if (faceUV && faceUV[f] === undefined) {
  33263. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33264. }
  33265. }
  33266. }
  33267. if (!flat) {
  33268. for (i = 0; i < data.vertex.length; i++) {
  33269. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  33270. uvs.push(0, 0);
  33271. }
  33272. for (f = 0; f < nbfaces; f++) {
  33273. for (i = 0; i < data.face[f].length - 2; i++) {
  33274. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  33275. }
  33276. }
  33277. }
  33278. else {
  33279. for (f = 0; f < nbfaces; f++) {
  33280. var fl = data.face[f].length; // number of vertices of the current face
  33281. ang = 2 * Math.PI / fl;
  33282. x = 0.5 * Math.tan(ang / 2);
  33283. y = 0.5;
  33284. // positions, uvs, colors
  33285. for (i = 0; i < fl; i++) {
  33286. // positions
  33287. 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);
  33288. indexes.push(index);
  33289. index++;
  33290. // uvs
  33291. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  33292. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  33293. uvs.push(u, v);
  33294. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  33295. y = x * Math.sin(ang) + y * Math.cos(ang);
  33296. x = tmp;
  33297. // colors
  33298. if (faceColors) {
  33299. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  33300. }
  33301. }
  33302. // indices from indexes
  33303. for (i = 0; i < fl - 2; i++) {
  33304. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  33305. }
  33306. faceIdx += fl;
  33307. }
  33308. }
  33309. VertexData.ComputeNormals(positions, indices, normals);
  33310. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33311. var vertexData = new VertexData();
  33312. vertexData.positions = positions;
  33313. vertexData.indices = indices;
  33314. vertexData.normals = normals;
  33315. vertexData.uvs = uvs;
  33316. if (faceColors && flat) {
  33317. vertexData.colors = colors;
  33318. }
  33319. return vertexData;
  33320. };
  33321. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  33322. /**
  33323. * Creates the VertexData of the Torus Knot.
  33324. */
  33325. VertexData.CreateTorusKnot = function (options) {
  33326. var indices = new Array();
  33327. var positions = new Array();
  33328. var normals = new Array();
  33329. var uvs = new Array();
  33330. var radius = options.radius || 2;
  33331. var tube = options.tube || 0.5;
  33332. var radialSegments = options.radialSegments || 32;
  33333. var tubularSegments = options.tubularSegments || 32;
  33334. var p = options.p || 2;
  33335. var q = options.q || 3;
  33336. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33337. // Helper
  33338. var getPos = function (angle) {
  33339. var cu = Math.cos(angle);
  33340. var su = Math.sin(angle);
  33341. var quOverP = q / p * angle;
  33342. var cs = Math.cos(quOverP);
  33343. var tx = radius * (2 + cs) * 0.5 * cu;
  33344. var ty = radius * (2 + cs) * su * 0.5;
  33345. var tz = radius * Math.sin(quOverP) * 0.5;
  33346. return new BABYLON.Vector3(tx, ty, tz);
  33347. };
  33348. // Vertices
  33349. var i;
  33350. var j;
  33351. for (i = 0; i <= radialSegments; i++) {
  33352. var modI = i % radialSegments;
  33353. var u = modI / radialSegments * 2 * p * Math.PI;
  33354. var p1 = getPos(u);
  33355. var p2 = getPos(u + 0.01);
  33356. var tang = p2.subtract(p1);
  33357. var n = p2.add(p1);
  33358. var bitan = BABYLON.Vector3.Cross(tang, n);
  33359. n = BABYLON.Vector3.Cross(bitan, tang);
  33360. bitan.normalize();
  33361. n.normalize();
  33362. for (j = 0; j < tubularSegments; j++) {
  33363. var modJ = j % tubularSegments;
  33364. var v = modJ / tubularSegments * 2 * Math.PI;
  33365. var cx = -tube * Math.cos(v);
  33366. var cy = tube * Math.sin(v);
  33367. positions.push(p1.x + cx * n.x + cy * bitan.x);
  33368. positions.push(p1.y + cx * n.y + cy * bitan.y);
  33369. positions.push(p1.z + cx * n.z + cy * bitan.z);
  33370. uvs.push(i / radialSegments);
  33371. uvs.push(j / tubularSegments);
  33372. }
  33373. }
  33374. for (i = 0; i < radialSegments; i++) {
  33375. for (j = 0; j < tubularSegments; j++) {
  33376. var jNext = (j + 1) % tubularSegments;
  33377. var a = i * tubularSegments + j;
  33378. var b = (i + 1) * tubularSegments + j;
  33379. var c = (i + 1) * tubularSegments + jNext;
  33380. var d = i * tubularSegments + jNext;
  33381. indices.push(d);
  33382. indices.push(b);
  33383. indices.push(a);
  33384. indices.push(d);
  33385. indices.push(c);
  33386. indices.push(b);
  33387. }
  33388. }
  33389. // Normals
  33390. VertexData.ComputeNormals(positions, indices, normals);
  33391. // Sides
  33392. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33393. // Result
  33394. var vertexData = new VertexData();
  33395. vertexData.indices = indices;
  33396. vertexData.positions = positions;
  33397. vertexData.normals = normals;
  33398. vertexData.uvs = uvs;
  33399. return vertexData;
  33400. };
  33401. // Tools
  33402. /**
  33403. * @param {any} - positions (number[] or Float32Array)
  33404. * @param {any} - indices (number[] or Uint16Array)
  33405. * @param {any} - normals (number[] or Float32Array)
  33406. * options (optional) :
  33407. * facetPositions : optional array of facet positions (vector3)
  33408. * facetNormals : optional array of facet normals (vector3)
  33409. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  33410. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  33411. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  33412. * bbSize : optional bounding box size data, required for facetPartitioning computation
  33413. * bInfo : optional bounding info, required for facetPartitioning computation
  33414. * useRightHandedSystem: optional boolean to for right handed system computation
  33415. * depthSort : optional boolean to enable the facet depth sort computation
  33416. * distanceTo : optional Vector3 to compute the facet depth from this location
  33417. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  33418. */
  33419. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  33420. // temporary scalar variables
  33421. var index = 0; // facet index
  33422. var p1p2x = 0.0; // p1p2 vector x coordinate
  33423. var p1p2y = 0.0; // p1p2 vector y coordinate
  33424. var p1p2z = 0.0; // p1p2 vector z coordinate
  33425. var p3p2x = 0.0; // p3p2 vector x coordinate
  33426. var p3p2y = 0.0; // p3p2 vector y coordinate
  33427. var p3p2z = 0.0; // p3p2 vector z coordinate
  33428. var faceNormalx = 0.0; // facet normal x coordinate
  33429. var faceNormaly = 0.0; // facet normal y coordinate
  33430. var faceNormalz = 0.0; // facet normal z coordinate
  33431. var length = 0.0; // facet normal length before normalization
  33432. var v1x = 0; // vector1 x index in the positions array
  33433. var v1y = 0; // vector1 y index in the positions array
  33434. var v1z = 0; // vector1 z index in the positions array
  33435. var v2x = 0; // vector2 x index in the positions array
  33436. var v2y = 0; // vector2 y index in the positions array
  33437. var v2z = 0; // vector2 z index in the positions array
  33438. var v3x = 0; // vector3 x index in the positions array
  33439. var v3y = 0; // vector3 y index in the positions array
  33440. var v3z = 0; // vector3 z index in the positions array
  33441. var computeFacetNormals = false;
  33442. var computeFacetPositions = false;
  33443. var computeFacetPartitioning = false;
  33444. var computeDepthSort = false;
  33445. var faceNormalSign = 1;
  33446. var ratio = 0;
  33447. var distanceTo = null;
  33448. if (options) {
  33449. computeFacetNormals = (options.facetNormals) ? true : false;
  33450. computeFacetPositions = (options.facetPositions) ? true : false;
  33451. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  33452. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  33453. ratio = options.ratio || 0;
  33454. computeDepthSort = (options.depthSort) ? true : false;
  33455. distanceTo = (options.distanceTo);
  33456. if (computeDepthSort) {
  33457. if (distanceTo === undefined) {
  33458. distanceTo = BABYLON.Vector3.Zero();
  33459. }
  33460. var depthSortedFacets = options.depthSortedFacets;
  33461. }
  33462. }
  33463. // facetPartitioning reinit if needed
  33464. var xSubRatio = 0;
  33465. var ySubRatio = 0;
  33466. var zSubRatio = 0;
  33467. var subSq = 0;
  33468. if (computeFacetPartitioning && options && options.bbSize) {
  33469. var ox = 0; // X partitioning index for facet position
  33470. var oy = 0; // Y partinioning index for facet position
  33471. var oz = 0; // Z partinioning index for facet position
  33472. var b1x = 0; // X partitioning index for facet v1 vertex
  33473. var b1y = 0; // Y partitioning index for facet v1 vertex
  33474. var b1z = 0; // z partitioning index for facet v1 vertex
  33475. var b2x = 0; // X partitioning index for facet v2 vertex
  33476. var b2y = 0; // Y partitioning index for facet v2 vertex
  33477. var b2z = 0; // Z partitioning index for facet v2 vertex
  33478. var b3x = 0; // X partitioning index for facet v3 vertex
  33479. var b3y = 0; // Y partitioning index for facet v3 vertex
  33480. var b3z = 0; // Z partitioning index for facet v3 vertex
  33481. var block_idx_o = 0; // facet barycenter block index
  33482. var block_idx_v1 = 0; // v1 vertex block index
  33483. var block_idx_v2 = 0; // v2 vertex block index
  33484. var block_idx_v3 = 0; // v3 vertex block index
  33485. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  33486. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  33487. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  33488. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  33489. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  33490. subSq = options.subDiv.max * options.subDiv.max;
  33491. options.facetPartitioning.length = 0;
  33492. }
  33493. // reset the normals
  33494. for (index = 0; index < positions.length; index++) {
  33495. normals[index] = 0.0;
  33496. }
  33497. // Loop : 1 indice triplet = 1 facet
  33498. var nbFaces = (indices.length / 3) | 0;
  33499. for (index = 0; index < nbFaces; index++) {
  33500. // get the indexes of the coordinates of each vertex of the facet
  33501. v1x = indices[index * 3] * 3;
  33502. v1y = v1x + 1;
  33503. v1z = v1x + 2;
  33504. v2x = indices[index * 3 + 1] * 3;
  33505. v2y = v2x + 1;
  33506. v2z = v2x + 2;
  33507. v3x = indices[index * 3 + 2] * 3;
  33508. v3y = v3x + 1;
  33509. v3z = v3x + 2;
  33510. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  33511. p1p2y = positions[v1y] - positions[v2y];
  33512. p1p2z = positions[v1z] - positions[v2z];
  33513. p3p2x = positions[v3x] - positions[v2x];
  33514. p3p2y = positions[v3y] - positions[v2y];
  33515. p3p2z = positions[v3z] - positions[v2z];
  33516. // compute the face normal with the cross product
  33517. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  33518. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  33519. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  33520. // normalize this normal and store it in the array facetData
  33521. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33522. length = (length === 0) ? 1.0 : length;
  33523. faceNormalx /= length;
  33524. faceNormaly /= length;
  33525. faceNormalz /= length;
  33526. if (computeFacetNormals && options) {
  33527. options.facetNormals[index].x = faceNormalx;
  33528. options.facetNormals[index].y = faceNormaly;
  33529. options.facetNormals[index].z = faceNormalz;
  33530. }
  33531. if (computeFacetPositions && options) {
  33532. // compute and the facet barycenter coordinates in the array facetPositions
  33533. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  33534. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  33535. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  33536. }
  33537. if (computeFacetPartitioning && options) {
  33538. // store the facet indexes in arrays in the main facetPartitioning array :
  33539. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  33540. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  33541. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  33542. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  33543. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33544. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33545. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33546. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33547. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33548. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33549. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33550. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33551. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33552. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  33553. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  33554. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  33555. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  33556. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  33557. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  33558. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  33559. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  33560. // push each facet index in each block containing the vertex
  33561. options.facetPartitioning[block_idx_v1].push(index);
  33562. if (block_idx_v2 != block_idx_v1) {
  33563. options.facetPartitioning[block_idx_v2].push(index);
  33564. }
  33565. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  33566. options.facetPartitioning[block_idx_v3].push(index);
  33567. }
  33568. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  33569. options.facetPartitioning[block_idx_o].push(index);
  33570. }
  33571. }
  33572. if (computeDepthSort && options && options.facetPositions) {
  33573. var dsf = depthSortedFacets[index];
  33574. dsf.ind = index * 3;
  33575. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  33576. }
  33577. // compute the normals anyway
  33578. normals[v1x] += faceNormalx; // accumulate all the normals per face
  33579. normals[v1y] += faceNormaly;
  33580. normals[v1z] += faceNormalz;
  33581. normals[v2x] += faceNormalx;
  33582. normals[v2y] += faceNormaly;
  33583. normals[v2z] += faceNormalz;
  33584. normals[v3x] += faceNormalx;
  33585. normals[v3y] += faceNormaly;
  33586. normals[v3z] += faceNormalz;
  33587. }
  33588. // last normalization of each normal
  33589. for (index = 0; index < normals.length / 3; index++) {
  33590. faceNormalx = normals[index * 3];
  33591. faceNormaly = normals[index * 3 + 1];
  33592. faceNormalz = normals[index * 3 + 2];
  33593. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33594. length = (length === 0) ? 1.0 : length;
  33595. faceNormalx /= length;
  33596. faceNormaly /= length;
  33597. faceNormalz /= length;
  33598. normals[index * 3] = faceNormalx;
  33599. normals[index * 3 + 1] = faceNormaly;
  33600. normals[index * 3 + 2] = faceNormalz;
  33601. }
  33602. };
  33603. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  33604. var li = indices.length;
  33605. var ln = normals.length;
  33606. var i;
  33607. var n;
  33608. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33609. switch (sideOrientation) {
  33610. case BABYLON.Mesh.FRONTSIDE:
  33611. // nothing changed
  33612. break;
  33613. case BABYLON.Mesh.BACKSIDE:
  33614. var tmp;
  33615. // indices
  33616. for (i = 0; i < li; i += 3) {
  33617. tmp = indices[i];
  33618. indices[i] = indices[i + 2];
  33619. indices[i + 2] = tmp;
  33620. }
  33621. // normals
  33622. for (n = 0; n < ln; n++) {
  33623. normals[n] = -normals[n];
  33624. }
  33625. break;
  33626. case BABYLON.Mesh.DOUBLESIDE:
  33627. // positions
  33628. var lp = positions.length;
  33629. var l = lp / 3;
  33630. for (var p = 0; p < lp; p++) {
  33631. positions[lp + p] = positions[p];
  33632. }
  33633. // indices
  33634. for (i = 0; i < li; i += 3) {
  33635. indices[i + li] = indices[i + 2] + l;
  33636. indices[i + 1 + li] = indices[i + 1] + l;
  33637. indices[i + 2 + li] = indices[i] + l;
  33638. }
  33639. // normals
  33640. for (n = 0; n < ln; n++) {
  33641. normals[ln + n] = -normals[n];
  33642. }
  33643. // uvs
  33644. var lu = uvs.length;
  33645. var u = 0;
  33646. for (u = 0; u < lu; u++) {
  33647. uvs[u + lu] = uvs[u];
  33648. }
  33649. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  33650. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  33651. u = 0;
  33652. for (i = 0; i < lu / 2; i++) {
  33653. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  33654. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  33655. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  33656. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  33657. u += 2;
  33658. }
  33659. break;
  33660. }
  33661. };
  33662. /**
  33663. * Creates a new VertexData from the imported parameters.
  33664. */
  33665. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  33666. var vertexData = new VertexData();
  33667. // positions
  33668. var positions = parsedVertexData.positions;
  33669. if (positions) {
  33670. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  33671. }
  33672. // normals
  33673. var normals = parsedVertexData.normals;
  33674. if (normals) {
  33675. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  33676. }
  33677. // tangents
  33678. var tangents = parsedVertexData.tangents;
  33679. if (tangents) {
  33680. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  33681. }
  33682. // uvs
  33683. var uvs = parsedVertexData.uvs;
  33684. if (uvs) {
  33685. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  33686. }
  33687. // uv2s
  33688. var uv2s = parsedVertexData.uv2s;
  33689. if (uv2s) {
  33690. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  33691. }
  33692. // uv3s
  33693. var uv3s = parsedVertexData.uv3s;
  33694. if (uv3s) {
  33695. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  33696. }
  33697. // uv4s
  33698. var uv4s = parsedVertexData.uv4s;
  33699. if (uv4s) {
  33700. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  33701. }
  33702. // uv5s
  33703. var uv5s = parsedVertexData.uv5s;
  33704. if (uv5s) {
  33705. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  33706. }
  33707. // uv6s
  33708. var uv6s = parsedVertexData.uv6s;
  33709. if (uv6s) {
  33710. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  33711. }
  33712. // colors
  33713. var colors = parsedVertexData.colors;
  33714. if (colors) {
  33715. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  33716. }
  33717. // matricesIndices
  33718. var matricesIndices = parsedVertexData.matricesIndices;
  33719. if (matricesIndices) {
  33720. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  33721. }
  33722. // matricesWeights
  33723. var matricesWeights = parsedVertexData.matricesWeights;
  33724. if (matricesWeights) {
  33725. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  33726. }
  33727. // indices
  33728. var indices = parsedVertexData.indices;
  33729. if (indices) {
  33730. vertexData.indices = indices;
  33731. }
  33732. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  33733. };
  33734. return VertexData;
  33735. }());
  33736. BABYLON.VertexData = VertexData;
  33737. })(BABYLON || (BABYLON = {}));
  33738. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  33739. var BABYLON;
  33740. (function (BABYLON) {
  33741. /**
  33742. * Class used to store geometry data (vertex buffers + index buffer)
  33743. */
  33744. var Geometry = /** @class */ (function () {
  33745. /**
  33746. * Creates a new geometry
  33747. * @param id defines the unique ID
  33748. * @param scene defines the hosting scene
  33749. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  33750. * @param updatable defines if geometry must be updatable (false by default)
  33751. * @param mesh defines the mesh that will be associated with the geometry
  33752. */
  33753. function Geometry(id, scene, vertexData, updatable, mesh) {
  33754. if (updatable === void 0) { updatable = false; }
  33755. if (mesh === void 0) { mesh = null; }
  33756. /**
  33757. * Gets the delay loading state of the geometry (none by default which means not delayed)
  33758. */
  33759. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  33760. this._totalVertices = 0;
  33761. this._isDisposed = false;
  33762. this._indexBufferIsUpdatable = false;
  33763. this.id = id;
  33764. this._engine = scene.getEngine();
  33765. this._meshes = [];
  33766. this._scene = scene;
  33767. //Init vertex buffer cache
  33768. this._vertexBuffers = {};
  33769. this._indices = [];
  33770. this._updatable = updatable;
  33771. // vertexData
  33772. if (vertexData) {
  33773. this.setAllVerticesData(vertexData, updatable);
  33774. }
  33775. else {
  33776. this._totalVertices = 0;
  33777. this._indices = [];
  33778. }
  33779. if (this._engine.getCaps().vertexArrayObject) {
  33780. this._vertexArrayObjects = {};
  33781. }
  33782. // applyToMesh
  33783. if (mesh) {
  33784. if (mesh.getClassName() === "LinesMesh") {
  33785. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  33786. this.updateExtend();
  33787. }
  33788. this.applyToMesh(mesh);
  33789. mesh.computeWorldMatrix(true);
  33790. }
  33791. }
  33792. Object.defineProperty(Geometry.prototype, "boundingBias", {
  33793. /**
  33794. * 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
  33795. */
  33796. get: function () {
  33797. return this._boundingBias;
  33798. },
  33799. /**
  33800. * 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
  33801. */
  33802. set: function (value) {
  33803. if (this._boundingBias && this._boundingBias.equals(value)) {
  33804. return;
  33805. }
  33806. this._boundingBias = value.clone();
  33807. this.updateBoundingInfo(true, null);
  33808. },
  33809. enumerable: true,
  33810. configurable: true
  33811. });
  33812. /**
  33813. * Static function used to attach a new empty geometry to a mesh
  33814. * @param mesh defines the mesh to attach the geometry to
  33815. * @returns the new {BABYLON.Geometry}
  33816. */
  33817. Geometry.CreateGeometryForMesh = function (mesh) {
  33818. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  33819. geometry.applyToMesh(mesh);
  33820. return geometry;
  33821. };
  33822. Object.defineProperty(Geometry.prototype, "extend", {
  33823. /**
  33824. * Gets the current extend of the geometry
  33825. */
  33826. get: function () {
  33827. return this._extend;
  33828. },
  33829. enumerable: true,
  33830. configurable: true
  33831. });
  33832. /**
  33833. * Gets the hosting scene
  33834. * @returns the hosting {BABYLON.Scene}
  33835. */
  33836. Geometry.prototype.getScene = function () {
  33837. return this._scene;
  33838. };
  33839. /**
  33840. * Gets the hosting engine
  33841. * @returns the hosting {BABYLON.Engine}
  33842. */
  33843. Geometry.prototype.getEngine = function () {
  33844. return this._engine;
  33845. };
  33846. /**
  33847. * Defines if the geometry is ready to use
  33848. * @returns true if the geometry is ready to be used
  33849. */
  33850. Geometry.prototype.isReady = function () {
  33851. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  33852. };
  33853. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  33854. /**
  33855. * Gets a value indicating that the geometry should not be serialized
  33856. */
  33857. get: function () {
  33858. for (var index = 0; index < this._meshes.length; index++) {
  33859. if (!this._meshes[index].doNotSerialize) {
  33860. return false;
  33861. }
  33862. }
  33863. return true;
  33864. },
  33865. enumerable: true,
  33866. configurable: true
  33867. });
  33868. /** @ignore */
  33869. Geometry.prototype._rebuild = function () {
  33870. if (this._vertexArrayObjects) {
  33871. this._vertexArrayObjects = {};
  33872. }
  33873. // Index buffer
  33874. if (this._meshes.length !== 0 && this._indices) {
  33875. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  33876. }
  33877. // Vertex buffers
  33878. for (var key in this._vertexBuffers) {
  33879. var vertexBuffer = this._vertexBuffers[key];
  33880. vertexBuffer._rebuild();
  33881. }
  33882. };
  33883. /**
  33884. * Affects all gemetry data in one call
  33885. * @param vertexData defines the geometry data
  33886. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  33887. */
  33888. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  33889. vertexData.applyToGeometry(this, updatable);
  33890. this.notifyUpdate();
  33891. };
  33892. /**
  33893. * Set specific vertex data
  33894. * @param kind defines the data kind (Position, normal, etc...)
  33895. * @param data defines the vertex data to use
  33896. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  33897. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  33898. */
  33899. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  33900. if (updatable === void 0) { updatable = false; }
  33901. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  33902. this.setVerticesBuffer(buffer);
  33903. };
  33904. /**
  33905. * Removes a specific vertex data
  33906. * @param kind defines the data kind (Position, normal, etc...)
  33907. */
  33908. Geometry.prototype.removeVerticesData = function (kind) {
  33909. if (this._vertexBuffers[kind]) {
  33910. this._vertexBuffers[kind].dispose();
  33911. delete this._vertexBuffers[kind];
  33912. }
  33913. };
  33914. /**
  33915. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  33916. * @param buffer defines the vertex buffer to use
  33917. */
  33918. Geometry.prototype.setVerticesBuffer = function (buffer) {
  33919. var kind = buffer.getKind();
  33920. if (this._vertexBuffers[kind]) {
  33921. this._vertexBuffers[kind].dispose();
  33922. }
  33923. this._vertexBuffers[kind] = buffer;
  33924. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33925. var data = buffer.getData();
  33926. var stride = buffer.getStrideSize();
  33927. this._totalVertices = data.length / stride;
  33928. this.updateExtend(data, stride);
  33929. this._resetPointsArrayCache();
  33930. var meshes = this._meshes;
  33931. var numOfMeshes = meshes.length;
  33932. for (var index = 0; index < numOfMeshes; index++) {
  33933. var mesh = meshes[index];
  33934. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33935. mesh._createGlobalSubMesh(false);
  33936. mesh.computeWorldMatrix(true);
  33937. }
  33938. }
  33939. this.notifyUpdate(kind);
  33940. if (this._vertexArrayObjects) {
  33941. this._disposeVertexArrayObjects();
  33942. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  33943. }
  33944. };
  33945. /**
  33946. * Update a specific vertex buffer
  33947. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  33948. * It will do nothing if the buffer is not updatable
  33949. * @param kind defines the data kind (Position, normal, etc...)
  33950. * @param data defines the data to use
  33951. * @param offset defines the offset in the target buffer where to store the data
  33952. */
  33953. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  33954. var vertexBuffer = this.getVertexBuffer(kind);
  33955. if (!vertexBuffer) {
  33956. return;
  33957. }
  33958. vertexBuffer.updateDirectly(data, offset);
  33959. this.notifyUpdate(kind);
  33960. };
  33961. /**
  33962. * Update a specific vertex buffer
  33963. * This function will create a new buffer if the current one is not updatable
  33964. * @param kind defines the data kind (Position, normal, etc...)
  33965. * @param data defines the data to use
  33966. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  33967. */
  33968. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  33969. if (updateExtends === void 0) { updateExtends = false; }
  33970. var vertexBuffer = this.getVertexBuffer(kind);
  33971. if (!vertexBuffer) {
  33972. return;
  33973. }
  33974. vertexBuffer.update(data);
  33975. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33976. var stride = vertexBuffer.getStrideSize();
  33977. this._totalVertices = data.length / stride;
  33978. this.updateBoundingInfo(updateExtends, data);
  33979. }
  33980. this.notifyUpdate(kind);
  33981. };
  33982. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  33983. if (updateExtends) {
  33984. this.updateExtend(data);
  33985. }
  33986. var meshes = this._meshes;
  33987. var numOfMeshes = meshes.length;
  33988. this._resetPointsArrayCache();
  33989. for (var index = 0; index < numOfMeshes; index++) {
  33990. var mesh = meshes[index];
  33991. if (updateExtends) {
  33992. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33993. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  33994. var subMesh = mesh.subMeshes[subIndex];
  33995. subMesh.refreshBoundingInfo();
  33996. }
  33997. }
  33998. }
  33999. };
  34000. /** @ignore */
  34001. Geometry.prototype._bind = function (effect, indexToBind) {
  34002. if (!effect) {
  34003. return;
  34004. }
  34005. if (indexToBind === undefined) {
  34006. indexToBind = this._indexBuffer;
  34007. }
  34008. var vbs = this.getVertexBuffers();
  34009. if (!vbs) {
  34010. return;
  34011. }
  34012. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34013. this._engine.bindBuffers(vbs, indexToBind, effect);
  34014. return;
  34015. }
  34016. // Using VAO
  34017. if (!this._vertexArrayObjects[effect.key]) {
  34018. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34019. }
  34020. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34021. };
  34022. /**
  34023. * Gets total number of vertices
  34024. * @returns the total number of vertices
  34025. */
  34026. Geometry.prototype.getTotalVertices = function () {
  34027. if (!this.isReady()) {
  34028. return 0;
  34029. }
  34030. return this._totalVertices;
  34031. };
  34032. /**
  34033. * Gets a specific vertex data attached to this geometry
  34034. * @param kind defines the data kind (Position, normal, etc...)
  34035. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34036. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34037. * @returns a float array containing vertex data
  34038. */
  34039. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34040. var vertexBuffer = this.getVertexBuffer(kind);
  34041. if (!vertexBuffer) {
  34042. return null;
  34043. }
  34044. var orig = vertexBuffer.getData();
  34045. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  34046. return orig;
  34047. }
  34048. else {
  34049. var len = orig.length;
  34050. var copy = [];
  34051. for (var i = 0; i < len; i++) {
  34052. copy.push(orig[i]);
  34053. }
  34054. return copy;
  34055. }
  34056. };
  34057. /**
  34058. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  34059. * @param kind defines the data kind (Position, normal, etc...)
  34060. * @returns true if the vertex buffer with the specified kind is updatable
  34061. */
  34062. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  34063. var vb = this._vertexBuffers[kind];
  34064. if (!vb) {
  34065. return false;
  34066. }
  34067. return vb.isUpdatable();
  34068. };
  34069. /**
  34070. * Gets a specific vertex buffer
  34071. * @param kind defines the data kind (Position, normal, etc...)
  34072. * @returns a {BABYLON.VertexBuffer}
  34073. */
  34074. Geometry.prototype.getVertexBuffer = function (kind) {
  34075. if (!this.isReady()) {
  34076. return null;
  34077. }
  34078. return this._vertexBuffers[kind];
  34079. };
  34080. /**
  34081. * Returns all vertex buffers
  34082. * @return an object holding all vertex buffers indexed by kind
  34083. */
  34084. Geometry.prototype.getVertexBuffers = function () {
  34085. if (!this.isReady()) {
  34086. return null;
  34087. }
  34088. return this._vertexBuffers;
  34089. };
  34090. /**
  34091. * Gets a boolean indicating if specific vertex buffer is present
  34092. * @param kind defines the data kind (Position, normal, etc...)
  34093. * @returns true if data is present
  34094. */
  34095. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34096. if (!this._vertexBuffers) {
  34097. if (this._delayInfo) {
  34098. return this._delayInfo.indexOf(kind) !== -1;
  34099. }
  34100. return false;
  34101. }
  34102. return this._vertexBuffers[kind] !== undefined;
  34103. };
  34104. /**
  34105. * Gets a list of all attached data kinds (Position, normal, etc...)
  34106. * @returns a list of string containing all kinds
  34107. */
  34108. Geometry.prototype.getVerticesDataKinds = function () {
  34109. var result = [];
  34110. var kind;
  34111. if (!this._vertexBuffers && this._delayInfo) {
  34112. for (kind in this._delayInfo) {
  34113. result.push(kind);
  34114. }
  34115. }
  34116. else {
  34117. for (kind in this._vertexBuffers) {
  34118. result.push(kind);
  34119. }
  34120. }
  34121. return result;
  34122. };
  34123. /**
  34124. * Update index buffer
  34125. * @param indices defines the indices to store in the index buffer
  34126. * @param offset defines the offset in the target buffer where to store the data
  34127. */
  34128. Geometry.prototype.updateIndices = function (indices, offset) {
  34129. if (!this._indexBuffer) {
  34130. return;
  34131. }
  34132. if (!this._indexBufferIsUpdatable) {
  34133. this.setIndices(indices, null, true);
  34134. }
  34135. else {
  34136. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  34137. }
  34138. };
  34139. /**
  34140. * Creates a new index buffer
  34141. * @param indices defines the indices to store in the index buffer
  34142. * @param totalVertices defines the total number of vertices (could be null)
  34143. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  34144. */
  34145. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  34146. if (totalVertices === void 0) { totalVertices = null; }
  34147. if (updatable === void 0) { updatable = false; }
  34148. if (this._indexBuffer) {
  34149. this._engine._releaseBuffer(this._indexBuffer);
  34150. }
  34151. this._disposeVertexArrayObjects();
  34152. this._indices = indices;
  34153. this._indexBufferIsUpdatable = updatable;
  34154. if (this._meshes.length !== 0 && this._indices) {
  34155. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  34156. }
  34157. if (totalVertices != undefined) {
  34158. this._totalVertices = totalVertices;
  34159. }
  34160. var meshes = this._meshes;
  34161. var numOfMeshes = meshes.length;
  34162. for (var index = 0; index < numOfMeshes; index++) {
  34163. meshes[index]._createGlobalSubMesh(true);
  34164. }
  34165. this.notifyUpdate();
  34166. };
  34167. /**
  34168. * Return the total number of indices
  34169. * @returns the total number of indices
  34170. */
  34171. Geometry.prototype.getTotalIndices = function () {
  34172. if (!this.isReady()) {
  34173. return 0;
  34174. }
  34175. return this._indices.length;
  34176. };
  34177. /**
  34178. * Gets the index buffer array
  34179. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34180. * @returns the index buffer array
  34181. */
  34182. Geometry.prototype.getIndices = function (copyWhenShared) {
  34183. if (!this.isReady()) {
  34184. return null;
  34185. }
  34186. var orig = this._indices;
  34187. if (!copyWhenShared || this._meshes.length === 1) {
  34188. return orig;
  34189. }
  34190. else {
  34191. var len = orig.length;
  34192. var copy = [];
  34193. for (var i = 0; i < len; i++) {
  34194. copy.push(orig[i]);
  34195. }
  34196. return copy;
  34197. }
  34198. };
  34199. /**
  34200. * Gets the index buffer
  34201. * @return the index buffer
  34202. */
  34203. Geometry.prototype.getIndexBuffer = function () {
  34204. if (!this.isReady()) {
  34205. return null;
  34206. }
  34207. return this._indexBuffer;
  34208. };
  34209. /** @ignore */
  34210. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  34211. if (effect === void 0) { effect = null; }
  34212. if (!effect || !this._vertexArrayObjects) {
  34213. return;
  34214. }
  34215. if (this._vertexArrayObjects[effect.key]) {
  34216. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  34217. delete this._vertexArrayObjects[effect.key];
  34218. }
  34219. };
  34220. /**
  34221. * Release the associated resources for a specific mesh
  34222. * @param mesh defines the source mesh
  34223. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  34224. */
  34225. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  34226. var meshes = this._meshes;
  34227. var index = meshes.indexOf(mesh);
  34228. if (index === -1) {
  34229. return;
  34230. }
  34231. meshes.splice(index, 1);
  34232. mesh._geometry = null;
  34233. if (meshes.length === 0 && shouldDispose) {
  34234. this.dispose();
  34235. }
  34236. };
  34237. /**
  34238. * Apply current geometry to a given mesh
  34239. * @param mesh defines the mesh to apply geometry to
  34240. */
  34241. Geometry.prototype.applyToMesh = function (mesh) {
  34242. if (mesh._geometry === this) {
  34243. return;
  34244. }
  34245. var previousGeometry = mesh._geometry;
  34246. if (previousGeometry) {
  34247. previousGeometry.releaseForMesh(mesh);
  34248. }
  34249. var meshes = this._meshes;
  34250. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  34251. mesh._geometry = this;
  34252. this._scene.pushGeometry(this);
  34253. meshes.push(mesh);
  34254. if (this.isReady()) {
  34255. this._applyToMesh(mesh);
  34256. }
  34257. else {
  34258. mesh._boundingInfo = this._boundingInfo;
  34259. }
  34260. };
  34261. Geometry.prototype.updateExtend = function (data, stride) {
  34262. if (data === void 0) { data = null; }
  34263. if (!data) {
  34264. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  34265. }
  34266. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  34267. };
  34268. Geometry.prototype._applyToMesh = function (mesh) {
  34269. var numOfMeshes = this._meshes.length;
  34270. // vertexBuffers
  34271. for (var kind in this._vertexBuffers) {
  34272. if (numOfMeshes === 1) {
  34273. this._vertexBuffers[kind].create();
  34274. }
  34275. var buffer = this._vertexBuffers[kind].getBuffer();
  34276. if (buffer)
  34277. buffer.references = numOfMeshes;
  34278. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34279. if (!this._extend) {
  34280. this.updateExtend(this._vertexBuffers[kind].getData());
  34281. }
  34282. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34283. mesh._createGlobalSubMesh(false);
  34284. //bounding info was just created again, world matrix should be applied again.
  34285. mesh._updateBoundingInfo();
  34286. }
  34287. }
  34288. // indexBuffer
  34289. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  34290. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34291. }
  34292. if (this._indexBuffer) {
  34293. this._indexBuffer.references = numOfMeshes;
  34294. }
  34295. };
  34296. Geometry.prototype.notifyUpdate = function (kind) {
  34297. if (this.onGeometryUpdated) {
  34298. this.onGeometryUpdated(this, kind);
  34299. }
  34300. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  34301. var mesh = _a[_i];
  34302. mesh._markSubMeshesAsAttributesDirty();
  34303. }
  34304. };
  34305. /**
  34306. * Load the geometry if it was flagged as delay loaded
  34307. * @param scene defines the hosting scene
  34308. * @param onLoaded defines a callback called when the geometry is loaded
  34309. */
  34310. Geometry.prototype.load = function (scene, onLoaded) {
  34311. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  34312. return;
  34313. }
  34314. if (this.isReady()) {
  34315. if (onLoaded) {
  34316. onLoaded();
  34317. }
  34318. return;
  34319. }
  34320. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  34321. this._queueLoad(scene, onLoaded);
  34322. };
  34323. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  34324. var _this = this;
  34325. if (!this.delayLoadingFile) {
  34326. return;
  34327. }
  34328. scene._addPendingData(this);
  34329. scene._loadFile(this.delayLoadingFile, function (data) {
  34330. if (!_this._delayLoadingFunction) {
  34331. return;
  34332. }
  34333. _this._delayLoadingFunction(JSON.parse(data), _this);
  34334. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34335. _this._delayInfo = [];
  34336. scene._removePendingData(_this);
  34337. var meshes = _this._meshes;
  34338. var numOfMeshes = meshes.length;
  34339. for (var index = 0; index < numOfMeshes; index++) {
  34340. _this._applyToMesh(meshes[index]);
  34341. }
  34342. if (onLoaded) {
  34343. onLoaded();
  34344. }
  34345. }, undefined, true);
  34346. };
  34347. /**
  34348. * Invert the geometry to move from a right handed system to a left handed one.
  34349. */
  34350. Geometry.prototype.toLeftHanded = function () {
  34351. // Flip faces
  34352. var tIndices = this.getIndices(false);
  34353. if (tIndices != null && tIndices.length > 0) {
  34354. for (var i = 0; i < tIndices.length; i += 3) {
  34355. var tTemp = tIndices[i + 0];
  34356. tIndices[i + 0] = tIndices[i + 2];
  34357. tIndices[i + 2] = tTemp;
  34358. }
  34359. this.setIndices(tIndices);
  34360. }
  34361. // Negate position.z
  34362. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  34363. if (tPositions != null && tPositions.length > 0) {
  34364. for (var i = 0; i < tPositions.length; i += 3) {
  34365. tPositions[i + 2] = -tPositions[i + 2];
  34366. }
  34367. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  34368. }
  34369. // Negate normal.z
  34370. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  34371. if (tNormals != null && tNormals.length > 0) {
  34372. for (var i = 0; i < tNormals.length; i += 3) {
  34373. tNormals[i + 2] = -tNormals[i + 2];
  34374. }
  34375. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  34376. }
  34377. };
  34378. // Cache
  34379. /** @ignore */
  34380. Geometry.prototype._resetPointsArrayCache = function () {
  34381. this._positions = null;
  34382. };
  34383. /** @ignore */
  34384. Geometry.prototype._generatePointsArray = function () {
  34385. if (this._positions)
  34386. return true;
  34387. this._positions = [];
  34388. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34389. if (!data) {
  34390. return false;
  34391. }
  34392. for (var index = 0; index < data.length; index += 3) {
  34393. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  34394. }
  34395. return true;
  34396. };
  34397. /**
  34398. * Gets a value indicating if the geometry is disposed
  34399. * @returns true if the geometry was disposed
  34400. */
  34401. Geometry.prototype.isDisposed = function () {
  34402. return this._isDisposed;
  34403. };
  34404. Geometry.prototype._disposeVertexArrayObjects = function () {
  34405. if (this._vertexArrayObjects) {
  34406. for (var kind in this._vertexArrayObjects) {
  34407. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  34408. }
  34409. this._vertexArrayObjects = {};
  34410. }
  34411. };
  34412. /**
  34413. * Free all associated resources
  34414. */
  34415. Geometry.prototype.dispose = function () {
  34416. var meshes = this._meshes;
  34417. var numOfMeshes = meshes.length;
  34418. var index;
  34419. for (index = 0; index < numOfMeshes; index++) {
  34420. this.releaseForMesh(meshes[index]);
  34421. }
  34422. this._meshes = [];
  34423. this._disposeVertexArrayObjects();
  34424. for (var kind in this._vertexBuffers) {
  34425. this._vertexBuffers[kind].dispose();
  34426. }
  34427. this._vertexBuffers = {};
  34428. this._totalVertices = 0;
  34429. if (this._indexBuffer) {
  34430. this._engine._releaseBuffer(this._indexBuffer);
  34431. }
  34432. this._indexBuffer = null;
  34433. this._indices = [];
  34434. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34435. this.delayLoadingFile = null;
  34436. this._delayLoadingFunction = null;
  34437. this._delayInfo = [];
  34438. this._boundingInfo = null;
  34439. this._scene.removeGeometry(this);
  34440. this._isDisposed = true;
  34441. };
  34442. /**
  34443. * Clone the current geometry into a new geometry
  34444. * @param id defines the unique ID of the new geometry
  34445. * @returns a new geometry object
  34446. */
  34447. Geometry.prototype.copy = function (id) {
  34448. var vertexData = new BABYLON.VertexData();
  34449. vertexData.indices = [];
  34450. var indices = this.getIndices();
  34451. if (indices) {
  34452. for (var index = 0; index < indices.length; index++) {
  34453. vertexData.indices.push(indices[index]);
  34454. }
  34455. }
  34456. var updatable = false;
  34457. var stopChecking = false;
  34458. var kind;
  34459. for (kind in this._vertexBuffers) {
  34460. // using slice() to make a copy of the array and not just reference it
  34461. var data = this.getVerticesData(kind);
  34462. if (data instanceof Float32Array) {
  34463. vertexData.set(new Float32Array(data), kind);
  34464. }
  34465. else {
  34466. vertexData.set(data.slice(0), kind);
  34467. }
  34468. if (!stopChecking) {
  34469. var vb = this.getVertexBuffer(kind);
  34470. if (vb) {
  34471. updatable = vb.isUpdatable();
  34472. stopChecking = !updatable;
  34473. }
  34474. }
  34475. }
  34476. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  34477. geometry.delayLoadState = this.delayLoadState;
  34478. geometry.delayLoadingFile = this.delayLoadingFile;
  34479. geometry._delayLoadingFunction = this._delayLoadingFunction;
  34480. for (kind in this._delayInfo) {
  34481. geometry._delayInfo = geometry._delayInfo || [];
  34482. geometry._delayInfo.push(kind);
  34483. }
  34484. // Bounding info
  34485. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34486. return geometry;
  34487. };
  34488. /**
  34489. * Serialize the current geometry info (and not the vertices data) into a JSON object
  34490. * @return a JSON representation of the current geometry data (without the vertices data)
  34491. */
  34492. Geometry.prototype.serialize = function () {
  34493. var serializationObject = {};
  34494. serializationObject.id = this.id;
  34495. serializationObject.updatable = this._updatable;
  34496. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  34497. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34498. }
  34499. return serializationObject;
  34500. };
  34501. Geometry.prototype.toNumberArray = function (origin) {
  34502. if (Array.isArray(origin)) {
  34503. return origin;
  34504. }
  34505. else {
  34506. return Array.prototype.slice.call(origin);
  34507. }
  34508. };
  34509. /**
  34510. * Serialize all vertices data into a JSON oject
  34511. * @returns a JSON representation of the current geometry data
  34512. */
  34513. Geometry.prototype.serializeVerticeData = function () {
  34514. var serializationObject = this.serialize();
  34515. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34516. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  34517. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34518. serializationObject.positions._updatable = true;
  34519. }
  34520. }
  34521. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34522. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  34523. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34524. serializationObject.normals._updatable = true;
  34525. }
  34526. }
  34527. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  34528. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  34529. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  34530. serializationObject.tangets._updatable = true;
  34531. }
  34532. }
  34533. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34534. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  34535. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  34536. serializationObject.uvs._updatable = true;
  34537. }
  34538. }
  34539. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34540. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  34541. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  34542. serializationObject.uv2s._updatable = true;
  34543. }
  34544. }
  34545. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  34546. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  34547. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  34548. serializationObject.uv3s._updatable = true;
  34549. }
  34550. }
  34551. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  34552. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  34553. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  34554. serializationObject.uv4s._updatable = true;
  34555. }
  34556. }
  34557. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  34558. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  34559. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  34560. serializationObject.uv5s._updatable = true;
  34561. }
  34562. }
  34563. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  34564. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  34565. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  34566. serializationObject.uv6s._updatable = true;
  34567. }
  34568. }
  34569. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34570. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  34571. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  34572. serializationObject.colors._updatable = true;
  34573. }
  34574. }
  34575. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34576. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  34577. serializationObject.matricesIndices._isExpanded = true;
  34578. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34579. serializationObject.matricesIndices._updatable = true;
  34580. }
  34581. }
  34582. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34583. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  34584. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34585. serializationObject.matricesWeights._updatable = true;
  34586. }
  34587. }
  34588. serializationObject.indices = this.toNumberArray(this.getIndices());
  34589. return serializationObject;
  34590. };
  34591. // Statics
  34592. /**
  34593. * Extracts a clone of a mesh geometry
  34594. * @param mesh defines the source mesh
  34595. * @param id defines the unique ID of the new geometry object
  34596. * @returns the new geometry object
  34597. */
  34598. Geometry.ExtractFromMesh = function (mesh, id) {
  34599. var geometry = mesh._geometry;
  34600. if (!geometry) {
  34601. return null;
  34602. }
  34603. return geometry.copy(id);
  34604. };
  34605. /**
  34606. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  34607. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  34608. * Be aware Math.random() could cause collisions, but:
  34609. * "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"
  34610. * @returns a string containing a new GUID
  34611. */
  34612. Geometry.RandomId = function () {
  34613. return BABYLON.Tools.RandomId();
  34614. };
  34615. /** @ignore */
  34616. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  34617. var scene = mesh.getScene();
  34618. // Geometry
  34619. var geometryId = parsedGeometry.geometryId;
  34620. if (geometryId) {
  34621. var geometry = scene.getGeometryByID(geometryId);
  34622. if (geometry) {
  34623. geometry.applyToMesh(mesh);
  34624. }
  34625. }
  34626. else if (parsedGeometry instanceof ArrayBuffer) {
  34627. var binaryInfo = mesh._binaryInfo;
  34628. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  34629. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  34630. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  34631. }
  34632. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  34633. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  34634. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  34635. }
  34636. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  34637. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  34638. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  34639. }
  34640. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  34641. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  34642. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  34643. }
  34644. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  34645. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  34646. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  34647. }
  34648. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  34649. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  34650. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  34651. }
  34652. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  34653. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  34654. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  34655. }
  34656. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  34657. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  34658. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  34659. }
  34660. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  34661. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  34662. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  34663. }
  34664. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  34665. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  34666. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  34667. }
  34668. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  34669. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  34670. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  34671. }
  34672. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  34673. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  34674. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  34675. }
  34676. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  34677. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  34678. mesh.setIndices(indicesData, null);
  34679. }
  34680. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  34681. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  34682. mesh.subMeshes = [];
  34683. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  34684. var materialIndex = subMeshesData[(i * 5) + 0];
  34685. var verticesStart = subMeshesData[(i * 5) + 1];
  34686. var verticesCount = subMeshesData[(i * 5) + 2];
  34687. var indexStart = subMeshesData[(i * 5) + 3];
  34688. var indexCount = subMeshesData[(i * 5) + 4];
  34689. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  34690. }
  34691. }
  34692. }
  34693. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  34694. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  34695. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  34696. if (parsedGeometry.tangents) {
  34697. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  34698. }
  34699. if (parsedGeometry.uvs) {
  34700. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  34701. }
  34702. if (parsedGeometry.uvs2) {
  34703. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  34704. }
  34705. if (parsedGeometry.uvs3) {
  34706. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  34707. }
  34708. if (parsedGeometry.uvs4) {
  34709. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  34710. }
  34711. if (parsedGeometry.uvs5) {
  34712. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  34713. }
  34714. if (parsedGeometry.uvs6) {
  34715. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  34716. }
  34717. if (parsedGeometry.colors) {
  34718. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  34719. }
  34720. if (parsedGeometry.matricesIndices) {
  34721. if (!parsedGeometry.matricesIndices._isExpanded) {
  34722. var floatIndices = [];
  34723. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  34724. var matricesIndex = parsedGeometry.matricesIndices[i];
  34725. floatIndices.push(matricesIndex & 0x000000FF);
  34726. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34727. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34728. floatIndices.push(matricesIndex >> 24);
  34729. }
  34730. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  34731. }
  34732. else {
  34733. delete parsedGeometry.matricesIndices._isExpanded;
  34734. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  34735. }
  34736. }
  34737. if (parsedGeometry.matricesIndicesExtra) {
  34738. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  34739. var floatIndices = [];
  34740. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  34741. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  34742. floatIndices.push(matricesIndex & 0x000000FF);
  34743. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34744. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34745. floatIndices.push(matricesIndex >> 24);
  34746. }
  34747. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  34748. }
  34749. else {
  34750. delete parsedGeometry.matricesIndices._isExpanded;
  34751. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  34752. }
  34753. }
  34754. if (parsedGeometry.matricesWeights) {
  34755. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  34756. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  34757. }
  34758. if (parsedGeometry.matricesWeightsExtra) {
  34759. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  34760. }
  34761. mesh.setIndices(parsedGeometry.indices, null);
  34762. }
  34763. // SubMeshes
  34764. if (parsedGeometry.subMeshes) {
  34765. mesh.subMeshes = [];
  34766. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  34767. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  34768. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  34769. }
  34770. }
  34771. // Flat shading
  34772. if (mesh._shouldGenerateFlatShading) {
  34773. mesh.convertToFlatShadedMesh();
  34774. delete mesh._shouldGenerateFlatShading;
  34775. }
  34776. // Update
  34777. mesh.computeWorldMatrix(true);
  34778. // Octree
  34779. var sceneOctree = scene.selectionOctree;
  34780. if (sceneOctree !== undefined && sceneOctree !== null) {
  34781. sceneOctree.addMesh(mesh);
  34782. }
  34783. };
  34784. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  34785. var epsilon = 1e-3;
  34786. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  34787. return;
  34788. }
  34789. var noInfluenceBoneIndex = 0.0;
  34790. if (parsedGeometry.skeletonId > -1) {
  34791. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  34792. if (!skeleton) {
  34793. return;
  34794. }
  34795. noInfluenceBoneIndex = skeleton.bones.length;
  34796. }
  34797. else {
  34798. return;
  34799. }
  34800. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34801. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34802. var matricesWeights = parsedGeometry.matricesWeights;
  34803. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  34804. var influencers = parsedGeometry.numBoneInfluencer;
  34805. var size = matricesWeights.length;
  34806. for (var i = 0; i < size; i += 4) {
  34807. var weight = 0.0;
  34808. var firstZeroWeight = -1;
  34809. for (var j = 0; j < 4; j++) {
  34810. var w = matricesWeights[i + j];
  34811. weight += w;
  34812. if (w < epsilon && firstZeroWeight < 0) {
  34813. firstZeroWeight = j;
  34814. }
  34815. }
  34816. if (matricesWeightsExtra) {
  34817. for (var j = 0; j < 4; j++) {
  34818. var w = matricesWeightsExtra[i + j];
  34819. weight += w;
  34820. if (w < epsilon && firstZeroWeight < 0) {
  34821. firstZeroWeight = j + 4;
  34822. }
  34823. }
  34824. }
  34825. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  34826. firstZeroWeight = influencers - 1;
  34827. }
  34828. if (weight > epsilon) {
  34829. var mweight = 1.0 / weight;
  34830. for (var j = 0; j < 4; j++) {
  34831. matricesWeights[i + j] *= mweight;
  34832. }
  34833. if (matricesWeightsExtra) {
  34834. for (var j = 0; j < 4; j++) {
  34835. matricesWeightsExtra[i + j] *= mweight;
  34836. }
  34837. }
  34838. }
  34839. else {
  34840. if (firstZeroWeight >= 4) {
  34841. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  34842. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  34843. }
  34844. else {
  34845. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  34846. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  34847. }
  34848. }
  34849. }
  34850. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  34851. if (parsedGeometry.matricesWeightsExtra) {
  34852. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  34853. }
  34854. };
  34855. /**
  34856. * Create a new geometry from persisted data (Using .babylon file format)
  34857. * @param parsedVertexData defines the persisted data
  34858. * @param scene defines the hosting scene
  34859. * @param rootUrl defines the root url to use to load assets (like delayed data)
  34860. * @returns the new geometry object
  34861. */
  34862. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  34863. if (scene.getGeometryByID(parsedVertexData.id)) {
  34864. return null; // null since geometry could be something else than a box...
  34865. }
  34866. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  34867. if (BABYLON.Tags) {
  34868. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  34869. }
  34870. if (parsedVertexData.delayLoadingFile) {
  34871. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  34872. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  34873. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  34874. geometry._delayInfo = [];
  34875. if (parsedVertexData.hasUVs) {
  34876. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  34877. }
  34878. if (parsedVertexData.hasUVs2) {
  34879. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  34880. }
  34881. if (parsedVertexData.hasUVs3) {
  34882. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  34883. }
  34884. if (parsedVertexData.hasUVs4) {
  34885. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  34886. }
  34887. if (parsedVertexData.hasUVs5) {
  34888. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  34889. }
  34890. if (parsedVertexData.hasUVs6) {
  34891. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  34892. }
  34893. if (parsedVertexData.hasColors) {
  34894. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  34895. }
  34896. if (parsedVertexData.hasMatricesIndices) {
  34897. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34898. }
  34899. if (parsedVertexData.hasMatricesWeights) {
  34900. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34901. }
  34902. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  34903. }
  34904. else {
  34905. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  34906. }
  34907. scene.pushGeometry(geometry, true);
  34908. return geometry;
  34909. };
  34910. return Geometry;
  34911. }());
  34912. BABYLON.Geometry = Geometry;
  34913. // Primitives
  34914. /// Abstract class
  34915. /**
  34916. * Abstract class used to provide common services for all typed geometries
  34917. */
  34918. var _PrimitiveGeometry = /** @class */ (function (_super) {
  34919. __extends(_PrimitiveGeometry, _super);
  34920. /**
  34921. * Creates a new typed geometry
  34922. * @param id defines the unique ID of the geometry
  34923. * @param scene defines the hosting scene
  34924. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34925. * @param mesh defines the hosting mesh (can be null)
  34926. */
  34927. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  34928. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  34929. if (mesh === void 0) { mesh = null; }
  34930. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  34931. _this._canBeRegenerated = _canBeRegenerated;
  34932. _this._beingRegenerated = true;
  34933. _this.regenerate();
  34934. _this._beingRegenerated = false;
  34935. return _this;
  34936. }
  34937. /**
  34938. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  34939. * @returns true if the geometry can be regenerated
  34940. */
  34941. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  34942. return this._canBeRegenerated;
  34943. };
  34944. /**
  34945. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  34946. */
  34947. _PrimitiveGeometry.prototype.regenerate = function () {
  34948. if (!this._canBeRegenerated) {
  34949. return;
  34950. }
  34951. this._beingRegenerated = true;
  34952. this.setAllVerticesData(this._regenerateVertexData(), false);
  34953. this._beingRegenerated = false;
  34954. };
  34955. /**
  34956. * Clone the geometry
  34957. * @param id defines the unique ID of the new geometry
  34958. * @returns the new geometry
  34959. */
  34960. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  34961. return _super.prototype.copy.call(this, id);
  34962. };
  34963. // overrides
  34964. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34965. if (!this._beingRegenerated) {
  34966. return;
  34967. }
  34968. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  34969. };
  34970. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  34971. if (!this._beingRegenerated) {
  34972. return;
  34973. }
  34974. _super.prototype.setVerticesData.call(this, kind, data, false);
  34975. };
  34976. // to override
  34977. /** @ignore */
  34978. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  34979. throw new Error("Abstract method");
  34980. };
  34981. _PrimitiveGeometry.prototype.copy = function (id) {
  34982. throw new Error("Must be overriden in sub-classes.");
  34983. };
  34984. _PrimitiveGeometry.prototype.serialize = function () {
  34985. var serializationObject = _super.prototype.serialize.call(this);
  34986. serializationObject.canBeRegenerated = this.canBeRegenerated();
  34987. return serializationObject;
  34988. };
  34989. return _PrimitiveGeometry;
  34990. }(Geometry));
  34991. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  34992. /**
  34993. * Creates a ribbon geometry
  34994. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  34995. */
  34996. var RibbonGeometry = /** @class */ (function (_super) {
  34997. __extends(RibbonGeometry, _super);
  34998. /**
  34999. * Creates a ribbon geometry
  35000. * @param id defines the unique ID of the geometry
  35001. * @param scene defines the hosting scene
  35002. * @param pathArray defines the array of paths to use
  35003. * @param closeArray defines if the last path and the first path must be joined
  35004. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35005. * @param offset defines the offset between points
  35006. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35007. * @param mesh defines the hosting mesh (can be null)
  35008. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35009. */
  35010. function RibbonGeometry(id, scene,
  35011. /**
  35012. * Defines the array of paths to use
  35013. */
  35014. pathArray,
  35015. /**
  35016. * Defines if the last and first points of each path in your pathArray must be joined
  35017. */
  35018. closeArray,
  35019. /**
  35020. * Defines if the last and first points of each path in your pathArray must be joined
  35021. */
  35022. closePath,
  35023. /**
  35024. * Defines the offset between points
  35025. */
  35026. offset, canBeRegenerated, mesh,
  35027. /**
  35028. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35029. */
  35030. side) {
  35031. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35032. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35033. _this.pathArray = pathArray;
  35034. _this.closeArray = closeArray;
  35035. _this.closePath = closePath;
  35036. _this.offset = offset;
  35037. _this.side = side;
  35038. return _this;
  35039. }
  35040. /** @ignore */
  35041. RibbonGeometry.prototype._regenerateVertexData = function () {
  35042. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35043. };
  35044. RibbonGeometry.prototype.copy = function (id) {
  35045. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  35046. };
  35047. return RibbonGeometry;
  35048. }(_PrimitiveGeometry));
  35049. BABYLON.RibbonGeometry = RibbonGeometry;
  35050. /**
  35051. * Creates a box geometry
  35052. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  35053. */
  35054. var BoxGeometry = /** @class */ (function (_super) {
  35055. __extends(BoxGeometry, _super);
  35056. /**
  35057. * Creates a box geometry
  35058. * @param id defines the unique ID of the geometry
  35059. * @param scene defines the hosting scene
  35060. * @param size defines the zise of the box (width, height and depth are the same)
  35061. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35062. * @param mesh defines the hosting mesh (can be null)
  35063. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35064. */
  35065. function BoxGeometry(id, scene,
  35066. /**
  35067. * Defines the zise of the box (width, height and depth are the same)
  35068. */
  35069. size, canBeRegenerated, mesh,
  35070. /**
  35071. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35072. */
  35073. side) {
  35074. if (mesh === void 0) { mesh = null; }
  35075. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35076. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35077. _this.size = size;
  35078. _this.side = side;
  35079. return _this;
  35080. }
  35081. BoxGeometry.prototype._regenerateVertexData = function () {
  35082. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35083. };
  35084. BoxGeometry.prototype.copy = function (id) {
  35085. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  35086. };
  35087. BoxGeometry.prototype.serialize = function () {
  35088. var serializationObject = _super.prototype.serialize.call(this);
  35089. serializationObject.size = this.size;
  35090. return serializationObject;
  35091. };
  35092. BoxGeometry.Parse = function (parsedBox, scene) {
  35093. if (scene.getGeometryByID(parsedBox.id)) {
  35094. return null; // null since geometry could be something else than a box...
  35095. }
  35096. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35097. if (BABYLON.Tags) {
  35098. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35099. }
  35100. scene.pushGeometry(box, true);
  35101. return box;
  35102. };
  35103. return BoxGeometry;
  35104. }(_PrimitiveGeometry));
  35105. BABYLON.BoxGeometry = BoxGeometry;
  35106. /**
  35107. * Creates a sphere geometry
  35108. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  35109. */
  35110. var SphereGeometry = /** @class */ (function (_super) {
  35111. __extends(SphereGeometry, _super);
  35112. /**
  35113. * Create a new sphere geometry
  35114. * @param id defines the unique ID of the geometry
  35115. * @param scene defines the hosting scene
  35116. * @param segments defines the number of segments to use to create the sphere
  35117. * @param diameter defines the diameter of the sphere
  35118. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35119. * @param mesh defines the hosting mesh (can be null)
  35120. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35121. */
  35122. function SphereGeometry(id, scene,
  35123. /**
  35124. * Defines the number of segments to use to create the sphere
  35125. */
  35126. segments,
  35127. /**
  35128. * Defines the diameter of the sphere
  35129. */
  35130. diameter, canBeRegenerated, mesh,
  35131. /**
  35132. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35133. */
  35134. side) {
  35135. if (mesh === void 0) { mesh = null; }
  35136. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35137. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35138. _this.segments = segments;
  35139. _this.diameter = diameter;
  35140. _this.side = side;
  35141. return _this;
  35142. }
  35143. SphereGeometry.prototype._regenerateVertexData = function () {
  35144. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35145. };
  35146. SphereGeometry.prototype.copy = function (id) {
  35147. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35148. };
  35149. SphereGeometry.prototype.serialize = function () {
  35150. var serializationObject = _super.prototype.serialize.call(this);
  35151. serializationObject.segments = this.segments;
  35152. serializationObject.diameter = this.diameter;
  35153. return serializationObject;
  35154. };
  35155. SphereGeometry.Parse = function (parsedSphere, scene) {
  35156. if (scene.getGeometryByID(parsedSphere.id)) {
  35157. return null; // null since geometry could be something else than a sphere...
  35158. }
  35159. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35160. if (BABYLON.Tags) {
  35161. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35162. }
  35163. scene.pushGeometry(sphere, true);
  35164. return sphere;
  35165. };
  35166. return SphereGeometry;
  35167. }(_PrimitiveGeometry));
  35168. BABYLON.SphereGeometry = SphereGeometry;
  35169. /**
  35170. * Creates a disc geometry
  35171. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  35172. */
  35173. var DiscGeometry = /** @class */ (function (_super) {
  35174. __extends(DiscGeometry, _super);
  35175. /**
  35176. * Creates a new disc geometry
  35177. * @param id defines the unique ID of the geometry
  35178. * @param scene defines the hosting scene
  35179. * @param radius defines the radius of the disc
  35180. * @param tessellation defines the tesselation factor to apply to the disc
  35181. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35182. * @param mesh defines the hosting mesh (can be null)
  35183. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35184. */
  35185. function DiscGeometry(id, scene,
  35186. /**
  35187. * Defines the radius of the disc
  35188. */
  35189. radius,
  35190. /**
  35191. * Defines the tesselation factor to apply to the disc
  35192. */
  35193. tessellation, canBeRegenerated, mesh,
  35194. /**
  35195. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35196. */
  35197. side) {
  35198. if (mesh === void 0) { mesh = null; }
  35199. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35200. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35201. _this.radius = radius;
  35202. _this.tessellation = tessellation;
  35203. _this.side = side;
  35204. return _this;
  35205. }
  35206. DiscGeometry.prototype._regenerateVertexData = function () {
  35207. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  35208. };
  35209. DiscGeometry.prototype.copy = function (id) {
  35210. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  35211. };
  35212. return DiscGeometry;
  35213. }(_PrimitiveGeometry));
  35214. BABYLON.DiscGeometry = DiscGeometry;
  35215. /**
  35216. * Creates a new cylinder geometry
  35217. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  35218. */
  35219. var CylinderGeometry = /** @class */ (function (_super) {
  35220. __extends(CylinderGeometry, _super);
  35221. /**
  35222. * Creates a new cylinder geometry
  35223. * @param id defines the unique ID of the geometry
  35224. * @param scene defines the hosting scene
  35225. * @param height defines the height of the cylinder
  35226. * @param diameterTop defines the diameter of the cylinder's top cap
  35227. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  35228. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  35229. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  35230. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35231. * @param mesh defines the hosting mesh (can be null)
  35232. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35233. */
  35234. function CylinderGeometry(id, scene,
  35235. /**
  35236. * Defines the height of the cylinder
  35237. */
  35238. height,
  35239. /**
  35240. * Defines the diameter of the cylinder's top cap
  35241. */
  35242. diameterTop,
  35243. /**
  35244. * Defines the diameter of the cylinder's bottom cap
  35245. */
  35246. diameterBottom,
  35247. /**
  35248. * Defines the tessellation factor to apply to the cylinder
  35249. */
  35250. tessellation,
  35251. /**
  35252. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  35253. */
  35254. subdivisions, canBeRegenerated, mesh,
  35255. /**
  35256. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35257. */
  35258. side) {
  35259. if (subdivisions === void 0) { subdivisions = 1; }
  35260. if (mesh === void 0) { mesh = null; }
  35261. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35262. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35263. _this.height = height;
  35264. _this.diameterTop = diameterTop;
  35265. _this.diameterBottom = diameterBottom;
  35266. _this.tessellation = tessellation;
  35267. _this.subdivisions = subdivisions;
  35268. _this.side = side;
  35269. return _this;
  35270. }
  35271. CylinderGeometry.prototype._regenerateVertexData = function () {
  35272. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  35273. };
  35274. CylinderGeometry.prototype.copy = function (id) {
  35275. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  35276. };
  35277. CylinderGeometry.prototype.serialize = function () {
  35278. var serializationObject = _super.prototype.serialize.call(this);
  35279. serializationObject.height = this.height;
  35280. serializationObject.diameterTop = this.diameterTop;
  35281. serializationObject.diameterBottom = this.diameterBottom;
  35282. serializationObject.tessellation = this.tessellation;
  35283. return serializationObject;
  35284. };
  35285. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  35286. if (scene.getGeometryByID(parsedCylinder.id)) {
  35287. return null; // null since geometry could be something else than a cylinder...
  35288. }
  35289. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  35290. if (BABYLON.Tags) {
  35291. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  35292. }
  35293. scene.pushGeometry(cylinder, true);
  35294. return cylinder;
  35295. };
  35296. return CylinderGeometry;
  35297. }(_PrimitiveGeometry));
  35298. BABYLON.CylinderGeometry = CylinderGeometry;
  35299. /**
  35300. * Creates a new torus geometry
  35301. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  35302. */
  35303. var TorusGeometry = /** @class */ (function (_super) {
  35304. __extends(TorusGeometry, _super);
  35305. /**
  35306. * Creates a new torus geometry
  35307. * @param id defines the unique ID of the geometry
  35308. * @param scene defines the hosting scene
  35309. * @param diameter defines the diameter of the torus
  35310. * @param thickness defines the thickness of the torus (ie. internal diameter)
  35311. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  35312. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35313. * @param mesh defines the hosting mesh (can be null)
  35314. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35315. */
  35316. function TorusGeometry(id, scene,
  35317. /**
  35318. * Defines the diameter of the torus
  35319. */
  35320. diameter,
  35321. /**
  35322. * Defines the thickness of the torus (ie. internal diameter)
  35323. */
  35324. thickness,
  35325. /**
  35326. * Defines the tesselation factor to apply to the torus
  35327. */
  35328. tessellation, canBeRegenerated, mesh,
  35329. /**
  35330. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35331. */
  35332. side) {
  35333. if (mesh === void 0) { mesh = null; }
  35334. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35335. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35336. _this.diameter = diameter;
  35337. _this.thickness = thickness;
  35338. _this.tessellation = tessellation;
  35339. _this.side = side;
  35340. return _this;
  35341. }
  35342. TorusGeometry.prototype._regenerateVertexData = function () {
  35343. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  35344. };
  35345. TorusGeometry.prototype.copy = function (id) {
  35346. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  35347. };
  35348. TorusGeometry.prototype.serialize = function () {
  35349. var serializationObject = _super.prototype.serialize.call(this);
  35350. serializationObject.diameter = this.diameter;
  35351. serializationObject.thickness = this.thickness;
  35352. serializationObject.tessellation = this.tessellation;
  35353. return serializationObject;
  35354. };
  35355. TorusGeometry.Parse = function (parsedTorus, scene) {
  35356. if (scene.getGeometryByID(parsedTorus.id)) {
  35357. return null; // null since geometry could be something else than a torus...
  35358. }
  35359. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  35360. if (BABYLON.Tags) {
  35361. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  35362. }
  35363. scene.pushGeometry(torus, true);
  35364. return torus;
  35365. };
  35366. return TorusGeometry;
  35367. }(_PrimitiveGeometry));
  35368. BABYLON.TorusGeometry = TorusGeometry;
  35369. /**
  35370. * Creates a new ground geometry
  35371. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  35372. */
  35373. var GroundGeometry = /** @class */ (function (_super) {
  35374. __extends(GroundGeometry, _super);
  35375. /**
  35376. * Creates a new ground geometry
  35377. * @param id defines the unique ID of the geometry
  35378. * @param scene defines the hosting scene
  35379. * @param width defines the width of the ground
  35380. * @param height defines the height of the ground
  35381. * @param subdivisions defines the subdivisions to apply to the ground
  35382. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35383. * @param mesh defines the hosting mesh (can be null)
  35384. */
  35385. function GroundGeometry(id, scene,
  35386. /**
  35387. * Defines the width of the ground
  35388. */
  35389. width,
  35390. /**
  35391. * Defines the height of the ground
  35392. */
  35393. height,
  35394. /**
  35395. * Defines the subdivisions to apply to the ground
  35396. */
  35397. subdivisions, canBeRegenerated, mesh) {
  35398. if (mesh === void 0) { mesh = null; }
  35399. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35400. _this.width = width;
  35401. _this.height = height;
  35402. _this.subdivisions = subdivisions;
  35403. return _this;
  35404. }
  35405. GroundGeometry.prototype._regenerateVertexData = function () {
  35406. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  35407. };
  35408. GroundGeometry.prototype.copy = function (id) {
  35409. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  35410. };
  35411. GroundGeometry.prototype.serialize = function () {
  35412. var serializationObject = _super.prototype.serialize.call(this);
  35413. serializationObject.width = this.width;
  35414. serializationObject.height = this.height;
  35415. serializationObject.subdivisions = this.subdivisions;
  35416. return serializationObject;
  35417. };
  35418. GroundGeometry.Parse = function (parsedGround, scene) {
  35419. if (scene.getGeometryByID(parsedGround.id)) {
  35420. return null; // null since geometry could be something else than a ground...
  35421. }
  35422. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  35423. if (BABYLON.Tags) {
  35424. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  35425. }
  35426. scene.pushGeometry(ground, true);
  35427. return ground;
  35428. };
  35429. return GroundGeometry;
  35430. }(_PrimitiveGeometry));
  35431. BABYLON.GroundGeometry = GroundGeometry;
  35432. /**
  35433. * Creates a tiled ground geometry
  35434. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  35435. */
  35436. var TiledGroundGeometry = /** @class */ (function (_super) {
  35437. __extends(TiledGroundGeometry, _super);
  35438. /**
  35439. * Creates a tiled ground geometry
  35440. * @param id defines the unique ID of the geometry
  35441. * @param scene defines the hosting scene
  35442. * @param xmin defines the minimum value on X axis
  35443. * @param zmin defines the minimum value on Z axis
  35444. * @param xmax defines the maximum value on X axis
  35445. * @param zmax defines the maximum value on Z axis
  35446. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  35447. * @param precision defines the precision to use when computing the tiles
  35448. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35449. * @param mesh defines the hosting mesh (can be null)
  35450. */
  35451. function TiledGroundGeometry(id, scene,
  35452. /**
  35453. * Defines the minimum value on X axis
  35454. */
  35455. xmin,
  35456. /**
  35457. * Defines the minimum value on Z axis
  35458. */
  35459. zmin,
  35460. /**
  35461. * Defines the maximum value on X axis
  35462. */
  35463. xmax,
  35464. /**
  35465. * Defines the maximum value on Z axis
  35466. */
  35467. zmax,
  35468. /**
  35469. * Defines the subdivisions to apply to the ground
  35470. */
  35471. subdivisions,
  35472. /**
  35473. * Defines the precision to use when computing the tiles
  35474. */
  35475. precision, canBeRegenerated, mesh) {
  35476. if (mesh === void 0) { mesh = null; }
  35477. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35478. _this.xmin = xmin;
  35479. _this.zmin = zmin;
  35480. _this.xmax = xmax;
  35481. _this.zmax = zmax;
  35482. _this.subdivisions = subdivisions;
  35483. _this.precision = precision;
  35484. return _this;
  35485. }
  35486. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  35487. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  35488. };
  35489. TiledGroundGeometry.prototype.copy = function (id) {
  35490. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  35491. };
  35492. return TiledGroundGeometry;
  35493. }(_PrimitiveGeometry));
  35494. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  35495. /**
  35496. * Creates a plane geometry
  35497. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  35498. */
  35499. var PlaneGeometry = /** @class */ (function (_super) {
  35500. __extends(PlaneGeometry, _super);
  35501. /**
  35502. * Creates a plane geometry
  35503. * @param id defines the unique ID of the geometry
  35504. * @param scene defines the hosting scene
  35505. * @param size defines the size of the plane (width === height)
  35506. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35507. * @param mesh defines the hosting mesh (can be null)
  35508. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35509. */
  35510. function PlaneGeometry(id, scene,
  35511. /**
  35512. * Defines the size of the plane (width === height)
  35513. */
  35514. size, canBeRegenerated, mesh,
  35515. /**
  35516. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35517. */
  35518. side) {
  35519. if (mesh === void 0) { mesh = null; }
  35520. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35521. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35522. _this.size = size;
  35523. _this.side = side;
  35524. return _this;
  35525. }
  35526. PlaneGeometry.prototype._regenerateVertexData = function () {
  35527. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  35528. };
  35529. PlaneGeometry.prototype.copy = function (id) {
  35530. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  35531. };
  35532. PlaneGeometry.prototype.serialize = function () {
  35533. var serializationObject = _super.prototype.serialize.call(this);
  35534. serializationObject.size = this.size;
  35535. return serializationObject;
  35536. };
  35537. PlaneGeometry.Parse = function (parsedPlane, scene) {
  35538. if (scene.getGeometryByID(parsedPlane.id)) {
  35539. return null; // null since geometry could be something else than a ground...
  35540. }
  35541. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  35542. if (BABYLON.Tags) {
  35543. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  35544. }
  35545. scene.pushGeometry(plane, true);
  35546. return plane;
  35547. };
  35548. return PlaneGeometry;
  35549. }(_PrimitiveGeometry));
  35550. BABYLON.PlaneGeometry = PlaneGeometry;
  35551. /**
  35552. * Creates a torus knot geometry
  35553. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  35554. */
  35555. var TorusKnotGeometry = /** @class */ (function (_super) {
  35556. __extends(TorusKnotGeometry, _super);
  35557. /**
  35558. * Creates a torus knot geometry
  35559. * @param id defines the unique ID of the geometry
  35560. * @param scene defines the hosting scene
  35561. * @param radius defines the radius of the torus knot
  35562. * @param tube defines the thickness of the torus knot tube
  35563. * @param radialSegments defines the number of radial segments
  35564. * @param tubularSegments defines the number of tubular segments
  35565. * @param p defines the first number of windings
  35566. * @param q defines the second number of windings
  35567. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35568. * @param mesh defines the hosting mesh (can be null)
  35569. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35570. */
  35571. function TorusKnotGeometry(id, scene,
  35572. /**
  35573. * Defines the radius of the torus knot
  35574. */
  35575. radius,
  35576. /**
  35577. * Defines the thickness of the torus knot tube
  35578. */
  35579. tube,
  35580. /**
  35581. * Defines the number of radial segments
  35582. */
  35583. radialSegments,
  35584. /**
  35585. * Defines the number of tubular segments
  35586. */
  35587. tubularSegments,
  35588. /**
  35589. * Defines the first number of windings
  35590. */
  35591. p,
  35592. /**
  35593. * Defines the second number of windings
  35594. */
  35595. q, canBeRegenerated, mesh,
  35596. /**
  35597. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35598. */
  35599. side) {
  35600. if (mesh === void 0) { mesh = null; }
  35601. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35602. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35603. _this.radius = radius;
  35604. _this.tube = tube;
  35605. _this.radialSegments = radialSegments;
  35606. _this.tubularSegments = tubularSegments;
  35607. _this.p = p;
  35608. _this.q = q;
  35609. _this.side = side;
  35610. return _this;
  35611. }
  35612. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  35613. 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 });
  35614. };
  35615. TorusKnotGeometry.prototype.copy = function (id) {
  35616. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  35617. };
  35618. TorusKnotGeometry.prototype.serialize = function () {
  35619. var serializationObject = _super.prototype.serialize.call(this);
  35620. serializationObject.radius = this.radius;
  35621. serializationObject.tube = this.tube;
  35622. serializationObject.radialSegments = this.radialSegments;
  35623. serializationObject.tubularSegments = this.tubularSegments;
  35624. serializationObject.p = this.p;
  35625. serializationObject.q = this.q;
  35626. return serializationObject;
  35627. };
  35628. ;
  35629. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  35630. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  35631. return null; // null since geometry could be something else than a ground...
  35632. }
  35633. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  35634. if (BABYLON.Tags) {
  35635. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  35636. }
  35637. scene.pushGeometry(torusKnot, true);
  35638. return torusKnot;
  35639. };
  35640. return TorusKnotGeometry;
  35641. }(_PrimitiveGeometry));
  35642. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  35643. //}
  35644. })(BABYLON || (BABYLON = {}));
  35645. //# sourceMappingURL=babylon.geometry.js.map
  35646. var BABYLON;
  35647. (function (BABYLON) {
  35648. /**
  35649. * PostProcessManager is used to manage one or more post processes or post process pipelines
  35650. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  35651. */
  35652. var PostProcessManager = /** @class */ (function () {
  35653. /**
  35654. * Creates a new instance of @see PostProcess
  35655. * @param scene The scene that the post process is associated with.
  35656. */
  35657. function PostProcessManager(scene) {
  35658. this._vertexBuffers = {};
  35659. this._scene = scene;
  35660. }
  35661. PostProcessManager.prototype._prepareBuffers = function () {
  35662. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  35663. return;
  35664. }
  35665. // VBO
  35666. var vertices = [];
  35667. vertices.push(1, 1);
  35668. vertices.push(-1, 1);
  35669. vertices.push(-1, -1);
  35670. vertices.push(1, -1);
  35671. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  35672. this._buildIndexBuffer();
  35673. };
  35674. PostProcessManager.prototype._buildIndexBuffer = function () {
  35675. // Indices
  35676. var indices = [];
  35677. indices.push(0);
  35678. indices.push(1);
  35679. indices.push(2);
  35680. indices.push(0);
  35681. indices.push(2);
  35682. indices.push(3);
  35683. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  35684. };
  35685. /**
  35686. * Rebuilds the vertex buffers of the manager.
  35687. */
  35688. PostProcessManager.prototype._rebuild = function () {
  35689. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  35690. if (!vb) {
  35691. return;
  35692. }
  35693. vb._rebuild();
  35694. this._buildIndexBuffer();
  35695. };
  35696. // Methods
  35697. /**
  35698. * Prepares a frame to be run through a post process.
  35699. * @param sourceTexture The input texture to the post procesess. (default: null)
  35700. * @param postProcesses An array of post processes to be run. (default: null)
  35701. * @returns True if the post processes were able to be run.
  35702. */
  35703. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  35704. if (sourceTexture === void 0) { sourceTexture = null; }
  35705. if (postProcesses === void 0) { postProcesses = null; }
  35706. var camera = this._scene.activeCamera;
  35707. if (!camera) {
  35708. return false;
  35709. }
  35710. var postProcesses = postProcesses || camera._postProcesses;
  35711. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  35712. return false;
  35713. }
  35714. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  35715. return true;
  35716. };
  35717. /**
  35718. * Manually render a set of post processes to a texture.
  35719. * @param postProcesses An array of post processes to be run.
  35720. * @param targetTexture The target texture to render to.
  35721. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  35722. */
  35723. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  35724. if (targetTexture === void 0) { targetTexture = null; }
  35725. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  35726. var engine = this._scene.getEngine();
  35727. for (var index = 0; index < postProcesses.length; index++) {
  35728. if (index < postProcesses.length - 1) {
  35729. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  35730. }
  35731. else {
  35732. if (targetTexture) {
  35733. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  35734. }
  35735. else {
  35736. engine.restoreDefaultFramebuffer();
  35737. }
  35738. }
  35739. var pp = postProcesses[index];
  35740. var effect = pp.apply();
  35741. if (effect) {
  35742. pp.onBeforeRenderObservable.notifyObservers(effect);
  35743. // VBOs
  35744. this._prepareBuffers();
  35745. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  35746. // Draw order
  35747. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  35748. pp.onAfterRenderObservable.notifyObservers(effect);
  35749. }
  35750. }
  35751. // Restore depth buffer
  35752. engine.setDepthBuffer(true);
  35753. engine.setDepthWrite(true);
  35754. };
  35755. /**
  35756. * Finalize the result of the output of the postprocesses.
  35757. * @param doNotPresent If true the result will not be displayed to the screen.
  35758. * @param targetTexture The target texture to render to.
  35759. * @param faceIndex The index of the face to bind the target texture to.
  35760. * @param postProcesses The array of post processes to render.
  35761. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  35762. */
  35763. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  35764. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  35765. var camera = this._scene.activeCamera;
  35766. if (!camera) {
  35767. return;
  35768. }
  35769. postProcesses = postProcesses || camera._postProcesses;
  35770. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  35771. return;
  35772. }
  35773. var engine = this._scene.getEngine();
  35774. for (var index = 0, len = postProcesses.length; index < len; index++) {
  35775. if (index < len - 1) {
  35776. postProcesses[index + 1].activate(camera, targetTexture);
  35777. }
  35778. else {
  35779. if (targetTexture) {
  35780. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  35781. }
  35782. else {
  35783. engine.restoreDefaultFramebuffer();
  35784. }
  35785. }
  35786. if (doNotPresent) {
  35787. break;
  35788. }
  35789. var pp = postProcesses[index];
  35790. var effect = pp.apply();
  35791. if (effect) {
  35792. pp.onBeforeRenderObservable.notifyObservers(effect);
  35793. // VBOs
  35794. this._prepareBuffers();
  35795. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  35796. // Draw order
  35797. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  35798. pp.onAfterRenderObservable.notifyObservers(effect);
  35799. }
  35800. }
  35801. // Restore states
  35802. engine.setDepthBuffer(true);
  35803. engine.setDepthWrite(true);
  35804. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  35805. };
  35806. /**
  35807. * Disposes of the post process manager.
  35808. */
  35809. PostProcessManager.prototype.dispose = function () {
  35810. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  35811. if (buffer) {
  35812. buffer.dispose();
  35813. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  35814. }
  35815. if (this._indexBuffer) {
  35816. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  35817. this._indexBuffer = null;
  35818. }
  35819. };
  35820. return PostProcessManager;
  35821. }());
  35822. BABYLON.PostProcessManager = PostProcessManager;
  35823. })(BABYLON || (BABYLON = {}));
  35824. //# sourceMappingURL=babylon.postProcessManager.js.map
  35825. var BABYLON;
  35826. (function (BABYLON) {
  35827. /**
  35828. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  35829. */
  35830. var PerformanceMonitor = /** @class */ (function () {
  35831. /**
  35832. * constructor
  35833. * @param frameSampleSize The number of samples required to saturate the sliding window
  35834. */
  35835. function PerformanceMonitor(frameSampleSize) {
  35836. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  35837. this._enabled = true;
  35838. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  35839. }
  35840. /**
  35841. * Samples current frame
  35842. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  35843. */
  35844. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  35845. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  35846. if (!this._enabled)
  35847. return;
  35848. if (this._lastFrameTimeMs != null) {
  35849. var dt = timeMs - this._lastFrameTimeMs;
  35850. this._rollingFrameTime.add(dt);
  35851. }
  35852. this._lastFrameTimeMs = timeMs;
  35853. };
  35854. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  35855. /**
  35856. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  35857. * @return Average frame time in milliseconds
  35858. */
  35859. get: function () {
  35860. return this._rollingFrameTime.average;
  35861. },
  35862. enumerable: true,
  35863. configurable: true
  35864. });
  35865. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  35866. /**
  35867. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  35868. * @return Frame time variance in milliseconds squared
  35869. */
  35870. get: function () {
  35871. return this._rollingFrameTime.variance;
  35872. },
  35873. enumerable: true,
  35874. configurable: true
  35875. });
  35876. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  35877. /**
  35878. * Returns the frame time of the most recent frame
  35879. * @return Frame time in milliseconds
  35880. */
  35881. get: function () {
  35882. return this._rollingFrameTime.history(0);
  35883. },
  35884. enumerable: true,
  35885. configurable: true
  35886. });
  35887. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  35888. /**
  35889. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  35890. * @return Framerate in frames per second
  35891. */
  35892. get: function () {
  35893. return 1000.0 / this._rollingFrameTime.average;
  35894. },
  35895. enumerable: true,
  35896. configurable: true
  35897. });
  35898. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  35899. /**
  35900. * Returns the average framerate in frames per second using the most recent frame time
  35901. * @return Framerate in frames per second
  35902. */
  35903. get: function () {
  35904. var history = this._rollingFrameTime.history(0);
  35905. if (history === 0) {
  35906. return 0;
  35907. }
  35908. return 1000.0 / history;
  35909. },
  35910. enumerable: true,
  35911. configurable: true
  35912. });
  35913. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  35914. /**
  35915. * Returns true if enough samples have been taken to completely fill the sliding window
  35916. * @return true if saturated
  35917. */
  35918. get: function () {
  35919. return this._rollingFrameTime.isSaturated();
  35920. },
  35921. enumerable: true,
  35922. configurable: true
  35923. });
  35924. /**
  35925. * Enables contributions to the sliding window sample set
  35926. */
  35927. PerformanceMonitor.prototype.enable = function () {
  35928. this._enabled = true;
  35929. };
  35930. /**
  35931. * Disables contributions to the sliding window sample set
  35932. * Samples will not be interpolated over the disabled period
  35933. */
  35934. PerformanceMonitor.prototype.disable = function () {
  35935. this._enabled = false;
  35936. //clear last sample to avoid interpolating over the disabled period when next enabled
  35937. this._lastFrameTimeMs = null;
  35938. };
  35939. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  35940. /**
  35941. * Returns true if sampling is enabled
  35942. * @return true if enabled
  35943. */
  35944. get: function () {
  35945. return this._enabled;
  35946. },
  35947. enumerable: true,
  35948. configurable: true
  35949. });
  35950. /**
  35951. * Resets performance monitor
  35952. */
  35953. PerformanceMonitor.prototype.reset = function () {
  35954. //clear last sample to avoid interpolating over the disabled period when next enabled
  35955. this._lastFrameTimeMs = null;
  35956. //wipe record
  35957. this._rollingFrameTime.reset();
  35958. };
  35959. return PerformanceMonitor;
  35960. }());
  35961. BABYLON.PerformanceMonitor = PerformanceMonitor;
  35962. /**
  35963. * RollingAverage
  35964. *
  35965. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  35966. */
  35967. var RollingAverage = /** @class */ (function () {
  35968. /**
  35969. * constructor
  35970. * @param length The number of samples required to saturate the sliding window
  35971. */
  35972. function RollingAverage(length) {
  35973. this._samples = new Array(length);
  35974. this.reset();
  35975. }
  35976. /**
  35977. * Adds a sample to the sample set
  35978. * @param v The sample value
  35979. */
  35980. RollingAverage.prototype.add = function (v) {
  35981. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  35982. var delta;
  35983. //we need to check if we've already wrapped round
  35984. if (this.isSaturated()) {
  35985. //remove bottom of stack from mean
  35986. var bottomValue = this._samples[this._pos];
  35987. delta = bottomValue - this.average;
  35988. this.average -= delta / (this._sampleCount - 1);
  35989. this._m2 -= delta * (bottomValue - this.average);
  35990. }
  35991. else {
  35992. this._sampleCount++;
  35993. }
  35994. //add new value to mean
  35995. delta = v - this.average;
  35996. this.average += delta / (this._sampleCount);
  35997. this._m2 += delta * (v - this.average);
  35998. //set the new variance
  35999. this.variance = this._m2 / (this._sampleCount - 1);
  36000. this._samples[this._pos] = v;
  36001. this._pos++;
  36002. this._pos %= this._samples.length; //positive wrap around
  36003. };
  36004. /**
  36005. * Returns previously added values or null if outside of history or outside the sliding window domain
  36006. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36007. * @return Value previously recorded with add() or null if outside of range
  36008. */
  36009. RollingAverage.prototype.history = function (i) {
  36010. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36011. return 0;
  36012. }
  36013. var i0 = this._wrapPosition(this._pos - 1.0);
  36014. return this._samples[this._wrapPosition(i0 - i)];
  36015. };
  36016. /**
  36017. * Returns true if enough samples have been taken to completely fill the sliding window
  36018. * @return true if sample-set saturated
  36019. */
  36020. RollingAverage.prototype.isSaturated = function () {
  36021. return this._sampleCount >= this._samples.length;
  36022. };
  36023. /**
  36024. * Resets the rolling average (equivalent to 0 samples taken so far)
  36025. */
  36026. RollingAverage.prototype.reset = function () {
  36027. this.average = 0;
  36028. this.variance = 0;
  36029. this._sampleCount = 0;
  36030. this._pos = 0;
  36031. this._m2 = 0;
  36032. };
  36033. /**
  36034. * Wraps a value around the sample range boundaries
  36035. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36036. * @return Wrapped position in sample range
  36037. */
  36038. RollingAverage.prototype._wrapPosition = function (i) {
  36039. var max = this._samples.length;
  36040. return ((i % max) + max) % max;
  36041. };
  36042. return RollingAverage;
  36043. }());
  36044. BABYLON.RollingAverage = RollingAverage;
  36045. })(BABYLON || (BABYLON = {}));
  36046. //# sourceMappingURL=babylon.performanceMonitor.js.map
  36047. var BABYLON;
  36048. (function (BABYLON) {
  36049. /**
  36050. * This groups together the common properties used for image processing either in direct forward pass
  36051. * or through post processing effect depending on the use of the image processing pipeline in your scene
  36052. * or not.
  36053. */
  36054. var ImageProcessingConfiguration = /** @class */ (function () {
  36055. function ImageProcessingConfiguration() {
  36056. /**
  36057. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  36058. */
  36059. this.colorCurves = new BABYLON.ColorCurves();
  36060. this._colorCurvesEnabled = false;
  36061. this._colorGradingEnabled = false;
  36062. this._colorGradingWithGreenDepth = true;
  36063. this._colorGradingBGR = true;
  36064. this._exposure = 1.0;
  36065. this._toneMappingEnabled = false;
  36066. this._contrast = 1.0;
  36067. /**
  36068. * Vignette stretch size.
  36069. */
  36070. this.vignetteStretch = 0;
  36071. /**
  36072. * Vignette centre X Offset.
  36073. */
  36074. this.vignetteCentreX = 0;
  36075. /**
  36076. * Vignette centre Y Offset.
  36077. */
  36078. this.vignetteCentreY = 0;
  36079. /**
  36080. * Vignette weight or intensity of the vignette effect.
  36081. */
  36082. this.vignetteWeight = 1.5;
  36083. /**
  36084. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  36085. * if vignetteEnabled is set to true.
  36086. */
  36087. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  36088. /**
  36089. * Camera field of view used by the Vignette effect.
  36090. */
  36091. this.vignetteCameraFov = 0.5;
  36092. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  36093. this._vignetteEnabled = false;
  36094. this._applyByPostProcess = false;
  36095. this._isEnabled = true;
  36096. /**
  36097. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  36098. * @type {BABYLON.Observable}
  36099. */
  36100. this.onUpdateParameters = new BABYLON.Observable();
  36101. }
  36102. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  36103. /**
  36104. * Gets wether the color curves effect is enabled.
  36105. */
  36106. get: function () {
  36107. return this._colorCurvesEnabled;
  36108. },
  36109. /**
  36110. * Sets wether the color curves effect is enabled.
  36111. */
  36112. set: function (value) {
  36113. if (this._colorCurvesEnabled === value) {
  36114. return;
  36115. }
  36116. this._colorCurvesEnabled = value;
  36117. this._updateParameters();
  36118. },
  36119. enumerable: true,
  36120. configurable: true
  36121. });
  36122. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  36123. /**
  36124. * Gets wether the color grading effect is enabled.
  36125. */
  36126. get: function () {
  36127. return this._colorGradingEnabled;
  36128. },
  36129. /**
  36130. * Sets wether the color grading effect is enabled.
  36131. */
  36132. set: function (value) {
  36133. if (this._colorGradingEnabled === value) {
  36134. return;
  36135. }
  36136. this._colorGradingEnabled = value;
  36137. this._updateParameters();
  36138. },
  36139. enumerable: true,
  36140. configurable: true
  36141. });
  36142. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  36143. /**
  36144. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  36145. */
  36146. get: function () {
  36147. return this._colorGradingWithGreenDepth;
  36148. },
  36149. /**
  36150. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  36151. */
  36152. set: function (value) {
  36153. if (this._colorGradingWithGreenDepth === value) {
  36154. return;
  36155. }
  36156. this._colorGradingWithGreenDepth = value;
  36157. this._updateParameters();
  36158. },
  36159. enumerable: true,
  36160. configurable: true
  36161. });
  36162. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  36163. /**
  36164. * Gets wether the color grading texture contains BGR values.
  36165. */
  36166. get: function () {
  36167. return this._colorGradingBGR;
  36168. },
  36169. /**
  36170. * Sets wether the color grading texture contains BGR values.
  36171. */
  36172. set: function (value) {
  36173. if (this._colorGradingBGR === value) {
  36174. return;
  36175. }
  36176. this._colorGradingBGR = value;
  36177. this._updateParameters();
  36178. },
  36179. enumerable: true,
  36180. configurable: true
  36181. });
  36182. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  36183. /**
  36184. * Gets the Exposure used in the effect.
  36185. */
  36186. get: function () {
  36187. return this._exposure;
  36188. },
  36189. /**
  36190. * Sets the Exposure used in the effect.
  36191. */
  36192. set: function (value) {
  36193. if (this._exposure === value) {
  36194. return;
  36195. }
  36196. this._exposure = value;
  36197. this._updateParameters();
  36198. },
  36199. enumerable: true,
  36200. configurable: true
  36201. });
  36202. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  36203. /**
  36204. * Gets wether the tone mapping effect is enabled.
  36205. */
  36206. get: function () {
  36207. return this._toneMappingEnabled;
  36208. },
  36209. /**
  36210. * Sets wether the tone mapping effect is enabled.
  36211. */
  36212. set: function (value) {
  36213. if (this._toneMappingEnabled === value) {
  36214. return;
  36215. }
  36216. this._toneMappingEnabled = value;
  36217. this._updateParameters();
  36218. },
  36219. enumerable: true,
  36220. configurable: true
  36221. });
  36222. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  36223. /**
  36224. * Gets the contrast used in the effect.
  36225. */
  36226. get: function () {
  36227. return this._contrast;
  36228. },
  36229. /**
  36230. * Sets the contrast used in the effect.
  36231. */
  36232. set: function (value) {
  36233. if (this._contrast === value) {
  36234. return;
  36235. }
  36236. this._contrast = value;
  36237. this._updateParameters();
  36238. },
  36239. enumerable: true,
  36240. configurable: true
  36241. });
  36242. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  36243. /**
  36244. * Gets the vignette blend mode allowing different kind of effect.
  36245. */
  36246. get: function () {
  36247. return this._vignetteBlendMode;
  36248. },
  36249. /**
  36250. * Sets the vignette blend mode allowing different kind of effect.
  36251. */
  36252. set: function (value) {
  36253. if (this._vignetteBlendMode === value) {
  36254. return;
  36255. }
  36256. this._vignetteBlendMode = value;
  36257. this._updateParameters();
  36258. },
  36259. enumerable: true,
  36260. configurable: true
  36261. });
  36262. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  36263. /**
  36264. * Gets wether the vignette effect is enabled.
  36265. */
  36266. get: function () {
  36267. return this._vignetteEnabled;
  36268. },
  36269. /**
  36270. * Sets wether the vignette effect is enabled.
  36271. */
  36272. set: function (value) {
  36273. if (this._vignetteEnabled === value) {
  36274. return;
  36275. }
  36276. this._vignetteEnabled = value;
  36277. this._updateParameters();
  36278. },
  36279. enumerable: true,
  36280. configurable: true
  36281. });
  36282. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  36283. /**
  36284. * Gets wether the image processing is applied through a post process or not.
  36285. */
  36286. get: function () {
  36287. return this._applyByPostProcess;
  36288. },
  36289. /**
  36290. * Sets wether the image processing is applied through a post process or not.
  36291. */
  36292. set: function (value) {
  36293. if (this._applyByPostProcess === value) {
  36294. return;
  36295. }
  36296. this._applyByPostProcess = value;
  36297. this._updateParameters();
  36298. },
  36299. enumerable: true,
  36300. configurable: true
  36301. });
  36302. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  36303. /**
  36304. * Gets wether the image processing is enabled or not.
  36305. */
  36306. get: function () {
  36307. return this._isEnabled;
  36308. },
  36309. /**
  36310. * Sets wether the image processing is enabled or not.
  36311. */
  36312. set: function (value) {
  36313. if (this._isEnabled === value) {
  36314. return;
  36315. }
  36316. this._isEnabled = value;
  36317. this._updateParameters();
  36318. },
  36319. enumerable: true,
  36320. configurable: true
  36321. });
  36322. /**
  36323. * Method called each time the image processing information changes requires to recompile the effect.
  36324. */
  36325. ImageProcessingConfiguration.prototype._updateParameters = function () {
  36326. this.onUpdateParameters.notifyObservers(this);
  36327. };
  36328. ImageProcessingConfiguration.prototype.getClassName = function () {
  36329. return "ImageProcessingConfiguration";
  36330. };
  36331. /**
  36332. * Prepare the list of uniforms associated with the Image Processing effects.
  36333. * @param uniformsList The list of uniforms used in the effect
  36334. * @param defines the list of defines currently in use
  36335. */
  36336. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  36337. if (defines.EXPOSURE) {
  36338. uniforms.push("exposureLinear");
  36339. }
  36340. if (defines.CONTRAST) {
  36341. uniforms.push("contrast");
  36342. }
  36343. if (defines.COLORGRADING) {
  36344. uniforms.push("colorTransformSettings");
  36345. }
  36346. if (defines.VIGNETTE) {
  36347. uniforms.push("vInverseScreenSize");
  36348. uniforms.push("vignetteSettings1");
  36349. uniforms.push("vignetteSettings2");
  36350. }
  36351. if (defines.COLORCURVES) {
  36352. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  36353. }
  36354. };
  36355. /**
  36356. * Prepare the list of samplers associated with the Image Processing effects.
  36357. * @param uniformsList The list of uniforms used in the effect
  36358. * @param defines the list of defines currently in use
  36359. */
  36360. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  36361. if (defines.COLORGRADING) {
  36362. samplersList.push("txColorTransform");
  36363. }
  36364. };
  36365. /**
  36366. * Prepare the list of defines associated to the shader.
  36367. * @param defines the list of defines to complete
  36368. */
  36369. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  36370. if (forPostProcess === void 0) { forPostProcess = false; }
  36371. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  36372. defines.VIGNETTE = false;
  36373. defines.TONEMAPPING = false;
  36374. defines.CONTRAST = false;
  36375. defines.EXPOSURE = false;
  36376. defines.COLORCURVES = false;
  36377. defines.COLORGRADING = false;
  36378. defines.COLORGRADING3D = false;
  36379. defines.IMAGEPROCESSING = false;
  36380. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  36381. return;
  36382. }
  36383. defines.VIGNETTE = this.vignetteEnabled;
  36384. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  36385. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  36386. defines.TONEMAPPING = this.toneMappingEnabled;
  36387. defines.CONTRAST = (this.contrast !== 1.0);
  36388. defines.EXPOSURE = (this.exposure !== 1.0);
  36389. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  36390. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  36391. if (defines.COLORGRADING) {
  36392. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  36393. }
  36394. else {
  36395. defines.COLORGRADING3D = false;
  36396. }
  36397. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  36398. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  36399. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  36400. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  36401. };
  36402. /**
  36403. * Returns true if all the image processing information are ready.
  36404. */
  36405. ImageProcessingConfiguration.prototype.isReady = function () {
  36406. // Color Grading texure can not be none blocking.
  36407. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  36408. };
  36409. /**
  36410. * Binds the image processing to the shader.
  36411. * @param effect The effect to bind to
  36412. */
  36413. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  36414. if (aspectRatio === void 0) { aspectRatio = 1; }
  36415. // Color Curves
  36416. if (this._colorCurvesEnabled && this.colorCurves) {
  36417. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  36418. }
  36419. // Vignette
  36420. if (this._vignetteEnabled) {
  36421. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  36422. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  36423. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  36424. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  36425. var vignetteScaleX = vignetteScaleY * aspectRatio;
  36426. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  36427. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  36428. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  36429. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  36430. var vignettePower = -2.0 * this.vignetteWeight;
  36431. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  36432. }
  36433. // Exposure
  36434. effect.setFloat("exposureLinear", this.exposure);
  36435. // Contrast
  36436. effect.setFloat("contrast", this.contrast);
  36437. // Color transform settings
  36438. if (this.colorGradingTexture) {
  36439. effect.setTexture("txColorTransform", this.colorGradingTexture);
  36440. var textureSize = this.colorGradingTexture.getSize().height;
  36441. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  36442. 0.5 / textureSize, // textureOffset
  36443. textureSize, // textureSize
  36444. this.colorGradingTexture.level // weight
  36445. );
  36446. }
  36447. };
  36448. /**
  36449. * Clones the current image processing instance.
  36450. * @return The cloned image processing
  36451. */
  36452. ImageProcessingConfiguration.prototype.clone = function () {
  36453. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  36454. };
  36455. /**
  36456. * Serializes the current image processing instance to a json representation.
  36457. * @return a JSON representation
  36458. */
  36459. ImageProcessingConfiguration.prototype.serialize = function () {
  36460. return BABYLON.SerializationHelper.Serialize(this);
  36461. };
  36462. /**
  36463. * Parses the image processing from a json representation.
  36464. * @param source the JSON source to parse
  36465. * @return The parsed image processing
  36466. */
  36467. ImageProcessingConfiguration.Parse = function (source) {
  36468. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  36469. };
  36470. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  36471. /**
  36472. * Used to apply the vignette as a mix with the pixel color.
  36473. */
  36474. get: function () {
  36475. return this._VIGNETTEMODE_MULTIPLY;
  36476. },
  36477. enumerable: true,
  36478. configurable: true
  36479. });
  36480. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  36481. /**
  36482. * Used to apply the vignette as a replacement of the pixel color.
  36483. */
  36484. get: function () {
  36485. return this._VIGNETTEMODE_OPAQUE;
  36486. },
  36487. enumerable: true,
  36488. configurable: true
  36489. });
  36490. // Static constants associated to the image processing.
  36491. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  36492. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  36493. __decorate([
  36494. BABYLON.serializeAsColorCurves()
  36495. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  36496. __decorate([
  36497. BABYLON.serialize()
  36498. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  36499. __decorate([
  36500. BABYLON.serializeAsTexture()
  36501. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  36502. __decorate([
  36503. BABYLON.serialize()
  36504. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  36505. __decorate([
  36506. BABYLON.serialize()
  36507. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  36508. __decorate([
  36509. BABYLON.serialize()
  36510. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  36511. __decorate([
  36512. BABYLON.serialize()
  36513. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  36514. __decorate([
  36515. BABYLON.serialize()
  36516. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  36517. __decorate([
  36518. BABYLON.serialize()
  36519. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  36520. __decorate([
  36521. BABYLON.serialize()
  36522. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  36523. __decorate([
  36524. BABYLON.serialize()
  36525. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  36526. __decorate([
  36527. BABYLON.serialize()
  36528. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  36529. __decorate([
  36530. BABYLON.serialize()
  36531. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  36532. __decorate([
  36533. BABYLON.serializeAsColor4()
  36534. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  36535. __decorate([
  36536. BABYLON.serialize()
  36537. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  36538. __decorate([
  36539. BABYLON.serialize()
  36540. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  36541. __decorate([
  36542. BABYLON.serialize()
  36543. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  36544. __decorate([
  36545. BABYLON.serialize()
  36546. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  36547. __decorate([
  36548. BABYLON.serialize()
  36549. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  36550. return ImageProcessingConfiguration;
  36551. }());
  36552. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  36553. })(BABYLON || (BABYLON = {}));
  36554. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  36555. var BABYLON;
  36556. (function (BABYLON) {
  36557. /**
  36558. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  36559. * It can help converting any input color in a desired output one. This can then be used to create effects
  36560. * from sepia, black and white to sixties or futuristic rendering...
  36561. *
  36562. * The only supported format is currently 3dl.
  36563. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  36564. */
  36565. var ColorGradingTexture = /** @class */ (function (_super) {
  36566. __extends(ColorGradingTexture, _super);
  36567. /**
  36568. * Instantiates a ColorGradingTexture from the following parameters.
  36569. *
  36570. * @param url The location of the color gradind data (currently only supporting 3dl)
  36571. * @param scene The scene the texture will be used in
  36572. */
  36573. function ColorGradingTexture(url, scene) {
  36574. var _this = _super.call(this, scene) || this;
  36575. if (!url) {
  36576. return _this;
  36577. }
  36578. _this._engine = scene.getEngine();
  36579. _this._textureMatrix = BABYLON.Matrix.Identity();
  36580. _this.name = url;
  36581. _this.url = url;
  36582. _this.hasAlpha = false;
  36583. _this.isCube = false;
  36584. _this.is3D = _this._engine.webGLVersion > 1;
  36585. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36586. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36587. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36588. _this.anisotropicFilteringLevel = 1;
  36589. _this._texture = _this._getFromCache(url, true);
  36590. if (!_this._texture) {
  36591. if (!scene.useDelayedTextureLoading) {
  36592. _this.loadTexture();
  36593. }
  36594. else {
  36595. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36596. }
  36597. }
  36598. return _this;
  36599. }
  36600. /**
  36601. * Returns the texture matrix used in most of the material.
  36602. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  36603. */
  36604. ColorGradingTexture.prototype.getTextureMatrix = function () {
  36605. return this._textureMatrix;
  36606. };
  36607. /**
  36608. * Occurs when the file being loaded is a .3dl LUT file.
  36609. */
  36610. ColorGradingTexture.prototype.load3dlTexture = function () {
  36611. var engine = this._engine;
  36612. var texture;
  36613. if (engine.webGLVersion === 1) {
  36614. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36615. }
  36616. else {
  36617. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36618. }
  36619. this._texture = texture;
  36620. var callback = function (text) {
  36621. if (typeof text !== "string") {
  36622. return;
  36623. }
  36624. var data = null;
  36625. var tempData = null;
  36626. var line;
  36627. var lines = text.split('\n');
  36628. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  36629. var maxColor = 0;
  36630. for (var i = 0; i < lines.length; i++) {
  36631. line = lines[i];
  36632. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  36633. continue;
  36634. if (line.indexOf('#') === 0)
  36635. continue;
  36636. var words = line.split(" ");
  36637. if (size === 0) {
  36638. // Number of space + one
  36639. size = words.length;
  36640. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  36641. tempData = new Float32Array(size * size * size * 4);
  36642. continue;
  36643. }
  36644. if (size != 0) {
  36645. var r = Math.max(parseInt(words[0]), 0);
  36646. var g = Math.max(parseInt(words[1]), 0);
  36647. var b = Math.max(parseInt(words[2]), 0);
  36648. maxColor = Math.max(r, maxColor);
  36649. maxColor = Math.max(g, maxColor);
  36650. maxColor = Math.max(b, maxColor);
  36651. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  36652. if (tempData) {
  36653. tempData[pixelStorageIndex + 0] = r;
  36654. tempData[pixelStorageIndex + 1] = g;
  36655. tempData[pixelStorageIndex + 2] = b;
  36656. }
  36657. pixelIndexSlice++;
  36658. if (pixelIndexSlice % size == 0) {
  36659. pixelIndexH++;
  36660. pixelIndexSlice = 0;
  36661. if (pixelIndexH % size == 0) {
  36662. pixelIndexW++;
  36663. pixelIndexH = 0;
  36664. }
  36665. }
  36666. }
  36667. }
  36668. if (tempData && data) {
  36669. for (var i = 0; i < tempData.length; i++) {
  36670. if (i > 0 && (i + 1) % 4 === 0) {
  36671. data[i] = 255;
  36672. }
  36673. else {
  36674. var value = tempData[i];
  36675. data[i] = (value / maxColor * 255);
  36676. }
  36677. }
  36678. }
  36679. if (texture.is3D) {
  36680. texture.updateSize(size, size, size);
  36681. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  36682. }
  36683. else {
  36684. texture.updateSize(size * size, size);
  36685. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  36686. }
  36687. };
  36688. var scene = this.getScene();
  36689. if (scene) {
  36690. scene._loadFile(this.url, callback);
  36691. }
  36692. else {
  36693. this._engine._loadFile(this.url, callback);
  36694. }
  36695. return this._texture;
  36696. };
  36697. /**
  36698. * Starts the loading process of the texture.
  36699. */
  36700. ColorGradingTexture.prototype.loadTexture = function () {
  36701. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  36702. this.load3dlTexture();
  36703. }
  36704. };
  36705. /**
  36706. * Clones the color gradind texture.
  36707. */
  36708. ColorGradingTexture.prototype.clone = function () {
  36709. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  36710. // Base texture
  36711. newTexture.level = this.level;
  36712. return newTexture;
  36713. };
  36714. /**
  36715. * Called during delayed load for textures.
  36716. */
  36717. ColorGradingTexture.prototype.delayLoad = function () {
  36718. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  36719. return;
  36720. }
  36721. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  36722. this._texture = this._getFromCache(this.url, true);
  36723. if (!this._texture) {
  36724. this.loadTexture();
  36725. }
  36726. };
  36727. /**
  36728. * Parses a color grading texture serialized by Babylon.
  36729. * @param parsedTexture The texture information being parsedTexture
  36730. * @param scene The scene to load the texture in
  36731. * @param rootUrl The root url of the data assets to load
  36732. * @return A color gradind texture
  36733. */
  36734. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  36735. var texture = null;
  36736. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  36737. texture = new ColorGradingTexture(parsedTexture.name, scene);
  36738. texture.name = parsedTexture.name;
  36739. texture.level = parsedTexture.level;
  36740. }
  36741. return texture;
  36742. };
  36743. /**
  36744. * Serializes the LUT texture to json format.
  36745. */
  36746. ColorGradingTexture.prototype.serialize = function () {
  36747. if (!this.name) {
  36748. return null;
  36749. }
  36750. var serializationObject = {};
  36751. serializationObject.name = this.name;
  36752. serializationObject.level = this.level;
  36753. serializationObject.customType = "BABYLON.ColorGradingTexture";
  36754. return serializationObject;
  36755. };
  36756. /**
  36757. * Empty line regex stored for GC.
  36758. */
  36759. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  36760. return ColorGradingTexture;
  36761. }(BABYLON.BaseTexture));
  36762. BABYLON.ColorGradingTexture = ColorGradingTexture;
  36763. })(BABYLON || (BABYLON = {}));
  36764. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  36765. var BABYLON;
  36766. (function (BABYLON) {
  36767. /**
  36768. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36769. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36770. * 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;
  36771. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36772. */
  36773. var ColorCurves = /** @class */ (function () {
  36774. function ColorCurves() {
  36775. this._dirty = true;
  36776. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  36777. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  36778. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  36779. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  36780. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  36781. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  36782. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  36783. this._globalHue = 30;
  36784. this._globalDensity = 0;
  36785. this._globalSaturation = 0;
  36786. this._globalExposure = 0;
  36787. this._highlightsHue = 30;
  36788. this._highlightsDensity = 0;
  36789. this._highlightsSaturation = 0;
  36790. this._highlightsExposure = 0;
  36791. this._midtonesHue = 30;
  36792. this._midtonesDensity = 0;
  36793. this._midtonesSaturation = 0;
  36794. this._midtonesExposure = 0;
  36795. this._shadowsHue = 30;
  36796. this._shadowsDensity = 0;
  36797. this._shadowsSaturation = 0;
  36798. this._shadowsExposure = 0;
  36799. }
  36800. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  36801. /**
  36802. * Gets the global Hue value.
  36803. * 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).
  36804. */
  36805. get: function () {
  36806. return this._globalHue;
  36807. },
  36808. /**
  36809. * Sets the global Hue value.
  36810. * 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).
  36811. */
  36812. set: function (value) {
  36813. this._globalHue = value;
  36814. this._dirty = true;
  36815. },
  36816. enumerable: true,
  36817. configurable: true
  36818. });
  36819. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  36820. /**
  36821. * Gets the global Density value.
  36822. * 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.
  36823. * Values less than zero provide a filter of opposite hue.
  36824. */
  36825. get: function () {
  36826. return this._globalDensity;
  36827. },
  36828. /**
  36829. * Sets the global Density value.
  36830. * 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.
  36831. * Values less than zero provide a filter of opposite hue.
  36832. */
  36833. set: function (value) {
  36834. this._globalDensity = value;
  36835. this._dirty = true;
  36836. },
  36837. enumerable: true,
  36838. configurable: true
  36839. });
  36840. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  36841. /**
  36842. * Gets the global Saturation value.
  36843. * 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.
  36844. */
  36845. get: function () {
  36846. return this._globalSaturation;
  36847. },
  36848. /**
  36849. * Sets the global Saturation value.
  36850. * 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.
  36851. */
  36852. set: function (value) {
  36853. this._globalSaturation = value;
  36854. this._dirty = true;
  36855. },
  36856. enumerable: true,
  36857. configurable: true
  36858. });
  36859. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  36860. /**
  36861. * Gets the highlights Hue value.
  36862. * 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).
  36863. */
  36864. get: function () {
  36865. return this._highlightsHue;
  36866. },
  36867. /**
  36868. * Sets the highlights Hue value.
  36869. * 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).
  36870. */
  36871. set: function (value) {
  36872. this._highlightsHue = value;
  36873. this._dirty = true;
  36874. },
  36875. enumerable: true,
  36876. configurable: true
  36877. });
  36878. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  36879. /**
  36880. * Gets the highlights Density value.
  36881. * 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.
  36882. * Values less than zero provide a filter of opposite hue.
  36883. */
  36884. get: function () {
  36885. return this._highlightsDensity;
  36886. },
  36887. /**
  36888. * Sets the highlights Density value.
  36889. * 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.
  36890. * Values less than zero provide a filter of opposite hue.
  36891. */
  36892. set: function (value) {
  36893. this._highlightsDensity = value;
  36894. this._dirty = true;
  36895. },
  36896. enumerable: true,
  36897. configurable: true
  36898. });
  36899. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  36900. /**
  36901. * Gets the highlights Saturation value.
  36902. * 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.
  36903. */
  36904. get: function () {
  36905. return this._highlightsSaturation;
  36906. },
  36907. /**
  36908. * Sets the highlights Saturation value.
  36909. * 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.
  36910. */
  36911. set: function (value) {
  36912. this._highlightsSaturation = value;
  36913. this._dirty = true;
  36914. },
  36915. enumerable: true,
  36916. configurable: true
  36917. });
  36918. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  36919. /**
  36920. * Gets the highlights Exposure value.
  36921. * 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.
  36922. */
  36923. get: function () {
  36924. return this._highlightsExposure;
  36925. },
  36926. /**
  36927. * Sets the highlights Exposure value.
  36928. * 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.
  36929. */
  36930. set: function (value) {
  36931. this._highlightsExposure = value;
  36932. this._dirty = true;
  36933. },
  36934. enumerable: true,
  36935. configurable: true
  36936. });
  36937. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  36938. /**
  36939. * Gets the midtones Hue value.
  36940. * 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).
  36941. */
  36942. get: function () {
  36943. return this._midtonesHue;
  36944. },
  36945. /**
  36946. * Sets the midtones Hue value.
  36947. * 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).
  36948. */
  36949. set: function (value) {
  36950. this._midtonesHue = value;
  36951. this._dirty = true;
  36952. },
  36953. enumerable: true,
  36954. configurable: true
  36955. });
  36956. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  36957. /**
  36958. * Gets the midtones Density value.
  36959. * 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.
  36960. * Values less than zero provide a filter of opposite hue.
  36961. */
  36962. get: function () {
  36963. return this._midtonesDensity;
  36964. },
  36965. /**
  36966. * Sets the midtones Density value.
  36967. * 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.
  36968. * Values less than zero provide a filter of opposite hue.
  36969. */
  36970. set: function (value) {
  36971. this._midtonesDensity = value;
  36972. this._dirty = true;
  36973. },
  36974. enumerable: true,
  36975. configurable: true
  36976. });
  36977. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  36978. /**
  36979. * Gets the midtones Saturation value.
  36980. * 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.
  36981. */
  36982. get: function () {
  36983. return this._midtonesSaturation;
  36984. },
  36985. /**
  36986. * Sets the midtones Saturation value.
  36987. * 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.
  36988. */
  36989. set: function (value) {
  36990. this._midtonesSaturation = value;
  36991. this._dirty = true;
  36992. },
  36993. enumerable: true,
  36994. configurable: true
  36995. });
  36996. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  36997. /**
  36998. * Gets the midtones Exposure value.
  36999. * 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.
  37000. */
  37001. get: function () {
  37002. return this._midtonesExposure;
  37003. },
  37004. /**
  37005. * Sets the midtones Exposure value.
  37006. * 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.
  37007. */
  37008. set: function (value) {
  37009. this._midtonesExposure = value;
  37010. this._dirty = true;
  37011. },
  37012. enumerable: true,
  37013. configurable: true
  37014. });
  37015. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  37016. /**
  37017. * Gets the shadows Hue value.
  37018. * 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).
  37019. */
  37020. get: function () {
  37021. return this._shadowsHue;
  37022. },
  37023. /**
  37024. * Sets the shadows Hue value.
  37025. * 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).
  37026. */
  37027. set: function (value) {
  37028. this._shadowsHue = value;
  37029. this._dirty = true;
  37030. },
  37031. enumerable: true,
  37032. configurable: true
  37033. });
  37034. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  37035. /**
  37036. * Gets the shadows Density value.
  37037. * 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.
  37038. * Values less than zero provide a filter of opposite hue.
  37039. */
  37040. get: function () {
  37041. return this._shadowsDensity;
  37042. },
  37043. /**
  37044. * Sets the shadows Density value.
  37045. * 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.
  37046. * Values less than zero provide a filter of opposite hue.
  37047. */
  37048. set: function (value) {
  37049. this._shadowsDensity = value;
  37050. this._dirty = true;
  37051. },
  37052. enumerable: true,
  37053. configurable: true
  37054. });
  37055. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  37056. /**
  37057. * Gets the shadows Saturation value.
  37058. * 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.
  37059. */
  37060. get: function () {
  37061. return this._shadowsSaturation;
  37062. },
  37063. /**
  37064. * Sets the shadows Saturation value.
  37065. * 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.
  37066. */
  37067. set: function (value) {
  37068. this._shadowsSaturation = value;
  37069. this._dirty = true;
  37070. },
  37071. enumerable: true,
  37072. configurable: true
  37073. });
  37074. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  37075. /**
  37076. * Gets the shadows Exposure value.
  37077. * 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.
  37078. */
  37079. get: function () {
  37080. return this._shadowsExposure;
  37081. },
  37082. /**
  37083. * Sets the shadows Exposure value.
  37084. * 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.
  37085. */
  37086. set: function (value) {
  37087. this._shadowsExposure = value;
  37088. this._dirty = true;
  37089. },
  37090. enumerable: true,
  37091. configurable: true
  37092. });
  37093. ColorCurves.prototype.getClassName = function () {
  37094. return "ColorCurves";
  37095. };
  37096. /**
  37097. * Binds the color curves to the shader.
  37098. * @param colorCurves The color curve to bind
  37099. * @param effect The effect to bind to
  37100. */
  37101. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  37102. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  37103. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  37104. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  37105. if (colorCurves._dirty) {
  37106. colorCurves._dirty = false;
  37107. // Fill in global info.
  37108. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  37109. // Compute highlights info.
  37110. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  37111. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  37112. // Compute midtones info.
  37113. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  37114. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  37115. // Compute shadows info.
  37116. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  37117. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  37118. // Compute deltas (neutral is midtones).
  37119. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  37120. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  37121. }
  37122. if (effect) {
  37123. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  37124. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  37125. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  37126. }
  37127. };
  37128. /**
  37129. * Prepare the list of uniforms associated with the ColorCurves effects.
  37130. * @param uniformsList The list of uniforms used in the effect
  37131. */
  37132. ColorCurves.PrepareUniforms = function (uniformsList) {
  37133. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  37134. };
  37135. /**
  37136. * Returns color grading data based on a hue, density, saturation and exposure value.
  37137. * @param filterHue The hue of the color filter.
  37138. * @param filterDensity The density of the color filter.
  37139. * @param saturation The saturation.
  37140. * @param exposure The exposure.
  37141. * @param result The result data container.
  37142. */
  37143. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  37144. if (hue == null) {
  37145. return;
  37146. }
  37147. hue = ColorCurves.clamp(hue, 0, 360);
  37148. density = ColorCurves.clamp(density, -100, 100);
  37149. saturation = ColorCurves.clamp(saturation, -100, 100);
  37150. exposure = ColorCurves.clamp(exposure, -100, 100);
  37151. // Remap the slider/config filter density with non-linear mapping and also scale by half
  37152. // so that the maximum filter density is only 50% control. This provides fine control
  37153. // for small values and reasonable range.
  37154. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  37155. density *= 0.5;
  37156. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  37157. if (density < 0) {
  37158. density *= -1;
  37159. hue = (hue + 180) % 360;
  37160. }
  37161. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  37162. result.scaleToRef(2, result);
  37163. result.a = 1 + 0.01 * saturation;
  37164. };
  37165. /**
  37166. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  37167. * @param value The input slider value in range [-100,100].
  37168. * @returns Adjusted value.
  37169. */
  37170. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  37171. value /= 100;
  37172. var x = Math.abs(value);
  37173. x = Math.pow(x, 2);
  37174. if (value < 0) {
  37175. x *= -1;
  37176. }
  37177. x *= 100;
  37178. return x;
  37179. };
  37180. /**
  37181. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  37182. * @param hue The hue (H) input.
  37183. * @param saturation The saturation (S) input.
  37184. * @param brightness The brightness (B) input.
  37185. * @result An RGBA color represented as Vector4.
  37186. */
  37187. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  37188. var h = ColorCurves.clamp(hue, 0, 360);
  37189. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  37190. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  37191. if (s === 0) {
  37192. result.r = v;
  37193. result.g = v;
  37194. result.b = v;
  37195. }
  37196. else {
  37197. // sector 0 to 5
  37198. h /= 60;
  37199. var i = Math.floor(h);
  37200. // fractional part of h
  37201. var f = h - i;
  37202. var p = v * (1 - s);
  37203. var q = v * (1 - s * f);
  37204. var t = v * (1 - s * (1 - f));
  37205. switch (i) {
  37206. case 0:
  37207. result.r = v;
  37208. result.g = t;
  37209. result.b = p;
  37210. break;
  37211. case 1:
  37212. result.r = q;
  37213. result.g = v;
  37214. result.b = p;
  37215. break;
  37216. case 2:
  37217. result.r = p;
  37218. result.g = v;
  37219. result.b = t;
  37220. break;
  37221. case 3:
  37222. result.r = p;
  37223. result.g = q;
  37224. result.b = v;
  37225. break;
  37226. case 4:
  37227. result.r = t;
  37228. result.g = p;
  37229. result.b = v;
  37230. break;
  37231. default:// case 5:
  37232. result.r = v;
  37233. result.g = p;
  37234. result.b = q;
  37235. break;
  37236. }
  37237. }
  37238. result.a = 1;
  37239. };
  37240. /**
  37241. * Returns a value clamped between min and max
  37242. * @param value The value to clamp
  37243. * @param min The minimum of value
  37244. * @param max The maximum of value
  37245. * @returns The clamped value.
  37246. */
  37247. ColorCurves.clamp = function (value, min, max) {
  37248. return Math.min(Math.max(value, min), max);
  37249. };
  37250. /**
  37251. * Clones the current color curve instance.
  37252. * @return The cloned curves
  37253. */
  37254. ColorCurves.prototype.clone = function () {
  37255. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  37256. };
  37257. /**
  37258. * Serializes the current color curve instance to a json representation.
  37259. * @return a JSON representation
  37260. */
  37261. ColorCurves.prototype.serialize = function () {
  37262. return BABYLON.SerializationHelper.Serialize(this);
  37263. };
  37264. /**
  37265. * Parses the color curve from a json representation.
  37266. * @param source the JSON source to parse
  37267. * @return The parsed curves
  37268. */
  37269. ColorCurves.Parse = function (source) {
  37270. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  37271. };
  37272. __decorate([
  37273. BABYLON.serialize()
  37274. ], ColorCurves.prototype, "_globalHue", void 0);
  37275. __decorate([
  37276. BABYLON.serialize()
  37277. ], ColorCurves.prototype, "_globalDensity", void 0);
  37278. __decorate([
  37279. BABYLON.serialize()
  37280. ], ColorCurves.prototype, "_globalSaturation", void 0);
  37281. __decorate([
  37282. BABYLON.serialize()
  37283. ], ColorCurves.prototype, "_globalExposure", void 0);
  37284. __decorate([
  37285. BABYLON.serialize()
  37286. ], ColorCurves.prototype, "_highlightsHue", void 0);
  37287. __decorate([
  37288. BABYLON.serialize()
  37289. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  37290. __decorate([
  37291. BABYLON.serialize()
  37292. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  37293. __decorate([
  37294. BABYLON.serialize()
  37295. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  37296. __decorate([
  37297. BABYLON.serialize()
  37298. ], ColorCurves.prototype, "_midtonesHue", void 0);
  37299. __decorate([
  37300. BABYLON.serialize()
  37301. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  37302. __decorate([
  37303. BABYLON.serialize()
  37304. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  37305. __decorate([
  37306. BABYLON.serialize()
  37307. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  37308. return ColorCurves;
  37309. }());
  37310. BABYLON.ColorCurves = ColorCurves;
  37311. })(BABYLON || (BABYLON = {}));
  37312. //# sourceMappingURL=babylon.colorCurves.js.map
  37313. //# sourceMappingURL=babylon.behavior.js.map
  37314. var BABYLON;
  37315. (function (BABYLON) {
  37316. /**
  37317. * "Static Class" containing the most commonly used helper while dealing with material for
  37318. * rendering purpose.
  37319. *
  37320. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  37321. *
  37322. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  37323. */
  37324. var MaterialHelper = /** @class */ (function () {
  37325. function MaterialHelper() {
  37326. }
  37327. /**
  37328. * Bind the current view position to an effect.
  37329. * @param effect The effect to be bound
  37330. * @param scene The scene the eyes position is used from
  37331. */
  37332. MaterialHelper.BindEyePosition = function (effect, scene) {
  37333. if (scene._forcedViewPosition) {
  37334. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  37335. return;
  37336. }
  37337. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  37338. };
  37339. /**
  37340. * Helps preparing the defines values about the UVs in used in the effect.
  37341. * UVs are shared as much as we can accross chanels in the shaders.
  37342. * @param texture The texture we are preparing the UVs for
  37343. * @param defines The defines to update
  37344. * @param key The chanel key "diffuse", "specular"... used in the shader
  37345. */
  37346. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  37347. defines._needUVs = true;
  37348. defines[key] = true;
  37349. if (texture.getTextureMatrix().isIdentity(true)) {
  37350. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  37351. if (texture.coordinatesIndex === 0) {
  37352. defines["MAINUV1"] = true;
  37353. }
  37354. else {
  37355. defines["MAINUV2"] = true;
  37356. }
  37357. }
  37358. else {
  37359. defines[key + "DIRECTUV"] = 0;
  37360. }
  37361. };
  37362. /**
  37363. * Binds a texture matrix value to its corrsponding uniform
  37364. * @param texture The texture to bind the matrix for
  37365. * @param uniformBuffer The uniform buffer receivin the data
  37366. * @param key The chanel key "diffuse", "specular"... used in the shader
  37367. */
  37368. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  37369. var matrix = texture.getTextureMatrix();
  37370. if (!matrix.isIdentity(true)) {
  37371. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  37372. }
  37373. };
  37374. /**
  37375. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  37376. * @param mesh defines the current mesh
  37377. * @param scene defines the current scene
  37378. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  37379. * @param pointsCloud defines if point cloud rendering has to be turned on
  37380. * @param fogEnabled defines if fog has to be turned on
  37381. * @param alphaTest defines if alpha testing has to be turned on
  37382. * @param defines defines the current list of defines
  37383. */
  37384. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  37385. if (defines._areMiscDirty) {
  37386. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  37387. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  37388. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  37389. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  37390. defines["ALPHATEST"] = alphaTest;
  37391. }
  37392. };
  37393. /**
  37394. * Helper used to prepare the list of defines associated with frame values for shader compilation
  37395. * @param scene defines the current scene
  37396. * @param engine defines the current engine
  37397. * @param defines specifies the list of active defines
  37398. * @param useInstances defines if instances have to be turned on
  37399. */
  37400. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances) {
  37401. var changed = false;
  37402. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  37403. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  37404. changed = true;
  37405. }
  37406. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  37407. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  37408. changed = true;
  37409. }
  37410. if (defines["INSTANCES"] !== useInstances) {
  37411. defines["INSTANCES"] = useInstances;
  37412. changed = true;
  37413. }
  37414. if (changed) {
  37415. defines.markAsUnprocessed();
  37416. }
  37417. };
  37418. /**
  37419. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  37420. * @param mesh The mesh containing the geometry data we will draw
  37421. * @param defines The defines to update
  37422. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  37423. * @param useBones Precise whether bones should be used or not (override mesh info)
  37424. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  37425. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  37426. * @returns false if defines are considered not dirty and have not been checked
  37427. */
  37428. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  37429. if (useMorphTargets === void 0) { useMorphTargets = false; }
  37430. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  37431. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  37432. return false;
  37433. }
  37434. defines._normals = defines._needNormals;
  37435. defines._uvs = defines._needUVs;
  37436. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  37437. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37438. defines["TANGENT"] = true;
  37439. }
  37440. if (defines._needUVs) {
  37441. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  37442. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  37443. }
  37444. else {
  37445. defines["UV1"] = false;
  37446. defines["UV2"] = false;
  37447. }
  37448. if (useVertexColor) {
  37449. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  37450. defines["VERTEXCOLOR"] = hasVertexColors;
  37451. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  37452. }
  37453. if (useBones) {
  37454. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  37455. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  37456. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  37457. }
  37458. else {
  37459. defines["NUM_BONE_INFLUENCERS"] = 0;
  37460. defines["BonesPerMesh"] = 0;
  37461. }
  37462. }
  37463. if (useMorphTargets) {
  37464. var manager = mesh.morphTargetManager;
  37465. if (manager) {
  37466. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  37467. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  37468. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  37469. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  37470. }
  37471. else {
  37472. defines["MORPHTARGETS_TANGENT"] = false;
  37473. defines["MORPHTARGETS_NORMAL"] = false;
  37474. defines["MORPHTARGETS"] = false;
  37475. defines["NUM_MORPH_INFLUENCERS"] = 0;
  37476. }
  37477. }
  37478. return true;
  37479. };
  37480. /**
  37481. * Prepares the defines related to the light information passed in parameter
  37482. * @param scene The scene we are intending to draw
  37483. * @param mesh The mesh the effect is compiling for
  37484. * @param defines The defines to update
  37485. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  37486. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  37487. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  37488. * @returns true if normals will be required for the rest of the effect
  37489. */
  37490. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  37491. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37492. if (disableLighting === void 0) { disableLighting = false; }
  37493. if (!defines._areLightsDirty) {
  37494. return defines._needNormals;
  37495. }
  37496. var lightIndex = 0;
  37497. var needNormals = false;
  37498. var needRebuild = false;
  37499. var lightmapMode = false;
  37500. var shadowEnabled = false;
  37501. var specularEnabled = false;
  37502. if (scene.lightsEnabled && !disableLighting) {
  37503. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  37504. var light = _a[_i];
  37505. needNormals = true;
  37506. if (defines["LIGHT" + lightIndex] === undefined) {
  37507. needRebuild = true;
  37508. }
  37509. defines["LIGHT" + lightIndex] = true;
  37510. defines["SPOTLIGHT" + lightIndex] = false;
  37511. defines["HEMILIGHT" + lightIndex] = false;
  37512. defines["POINTLIGHT" + lightIndex] = false;
  37513. defines["DIRLIGHT" + lightIndex] = false;
  37514. var type;
  37515. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  37516. type = "SPOTLIGHT" + lightIndex;
  37517. var spotLight = light;
  37518. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  37519. }
  37520. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  37521. type = "HEMILIGHT" + lightIndex;
  37522. }
  37523. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  37524. type = "POINTLIGHT" + lightIndex;
  37525. }
  37526. else {
  37527. type = "DIRLIGHT" + lightIndex;
  37528. }
  37529. defines[type] = true;
  37530. // Specular
  37531. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  37532. specularEnabled = true;
  37533. }
  37534. // Shadows
  37535. defines["SHADOW" + lightIndex] = false;
  37536. defines["SHADOWPCF" + lightIndex] = false;
  37537. defines["SHADOWESM" + lightIndex] = false;
  37538. defines["SHADOWCUBE" + lightIndex] = false;
  37539. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  37540. var shadowGenerator = light.getShadowGenerator();
  37541. if (shadowGenerator) {
  37542. shadowEnabled = true;
  37543. shadowGenerator.prepareDefines(defines, lightIndex);
  37544. }
  37545. }
  37546. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  37547. lightmapMode = true;
  37548. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  37549. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  37550. }
  37551. else {
  37552. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  37553. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  37554. }
  37555. lightIndex++;
  37556. if (lightIndex === maxSimultaneousLights)
  37557. break;
  37558. }
  37559. }
  37560. defines["SPECULARTERM"] = specularEnabled;
  37561. defines["SHADOWS"] = shadowEnabled;
  37562. // Resetting all other lights if any
  37563. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  37564. if (defines["LIGHT" + index] !== undefined) {
  37565. defines["LIGHT" + index] = false;
  37566. defines["HEMILIGHT" + lightIndex] = false;
  37567. defines["POINTLIGHT" + lightIndex] = false;
  37568. defines["DIRLIGHT" + lightIndex] = false;
  37569. defines["SPOTLIGHT" + lightIndex] = false;
  37570. defines["SHADOW" + lightIndex] = false;
  37571. }
  37572. }
  37573. var caps = scene.getEngine().getCaps();
  37574. if (defines["SHADOWFLOAT"] === undefined) {
  37575. needRebuild = true;
  37576. }
  37577. defines["SHADOWFLOAT"] = shadowEnabled &&
  37578. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  37579. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  37580. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  37581. if (needRebuild) {
  37582. defines.rebuild();
  37583. }
  37584. return needNormals;
  37585. };
  37586. /**
  37587. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  37588. * that won t be acctive due to defines being turned off.
  37589. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  37590. * @param samplersList The samplers list
  37591. * @param defines The defines helping in the list generation
  37592. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  37593. */
  37594. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  37595. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37596. var uniformsList;
  37597. var uniformBuffersList = null;
  37598. if (uniformsListOrOptions.uniformsNames) {
  37599. var options = uniformsListOrOptions;
  37600. uniformsList = options.uniformsNames;
  37601. uniformBuffersList = options.uniformBuffersNames;
  37602. samplersList = options.samplers;
  37603. defines = options.defines;
  37604. maxSimultaneousLights = options.maxSimultaneousLights;
  37605. }
  37606. else {
  37607. uniformsList = uniformsListOrOptions;
  37608. if (!samplersList) {
  37609. samplersList = [];
  37610. }
  37611. }
  37612. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  37613. if (!defines["LIGHT" + lightIndex]) {
  37614. break;
  37615. }
  37616. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  37617. if (uniformBuffersList) {
  37618. uniformBuffersList.push("Light" + lightIndex);
  37619. }
  37620. samplersList.push("shadowSampler" + lightIndex);
  37621. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  37622. samplersList.push("projectionLightSampler" + lightIndex);
  37623. uniformsList.push("textureProjectionMatrix" + lightIndex);
  37624. }
  37625. }
  37626. if (defines["NUM_MORPH_INFLUENCERS"]) {
  37627. uniformsList.push("morphTargetInfluences");
  37628. }
  37629. };
  37630. /**
  37631. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  37632. * @param defines The defines to update while falling back
  37633. * @param fallbacks The authorized effect fallbacks
  37634. * @param maxSimultaneousLights The maximum number of lights allowed
  37635. * @param rank the current rank of the Effect
  37636. * @returns The newly affected rank
  37637. */
  37638. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  37639. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37640. if (rank === void 0) { rank = 0; }
  37641. var lightFallbackRank = 0;
  37642. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  37643. if (!defines["LIGHT" + lightIndex]) {
  37644. break;
  37645. }
  37646. if (lightIndex > 0) {
  37647. lightFallbackRank = rank + lightIndex;
  37648. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  37649. }
  37650. if (!defines["SHADOWS"]) {
  37651. if (defines["SHADOW" + lightIndex]) {
  37652. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  37653. }
  37654. if (defines["SHADOWPCF" + lightIndex]) {
  37655. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  37656. }
  37657. if (defines["SHADOWESM" + lightIndex]) {
  37658. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  37659. }
  37660. }
  37661. }
  37662. return lightFallbackRank++;
  37663. };
  37664. /**
  37665. * Prepares the list of attributes required for morph targets according to the effect defines.
  37666. * @param attribs The current list of supported attribs
  37667. * @param mesh The mesh to prepare the morph targets attributes for
  37668. * @param defines The current Defines of the effect
  37669. */
  37670. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  37671. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  37672. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  37673. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  37674. var manager = mesh.morphTargetManager;
  37675. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  37676. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  37677. for (var index = 0; index < influencers; index++) {
  37678. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  37679. if (normal) {
  37680. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  37681. }
  37682. if (tangent) {
  37683. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  37684. }
  37685. if (attribs.length > maxAttributesCount) {
  37686. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  37687. }
  37688. }
  37689. }
  37690. };
  37691. /**
  37692. * Prepares the list of attributes required for bones according to the effect defines.
  37693. * @param attribs The current list of supported attribs
  37694. * @param mesh The mesh to prepare the bones attributes for
  37695. * @param defines The current Defines of the effect
  37696. * @param fallbacks The current efffect fallback strategy
  37697. */
  37698. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  37699. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  37700. fallbacks.addCPUSkinningFallback(0, mesh);
  37701. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37702. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37703. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  37704. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  37705. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  37706. }
  37707. }
  37708. };
  37709. /**
  37710. * Prepares the list of attributes required for instances according to the effect defines.
  37711. * @param attribs The current list of supported attribs
  37712. * @param defines The current Defines of the effect
  37713. */
  37714. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  37715. if (defines["INSTANCES"]) {
  37716. attribs.push("world0");
  37717. attribs.push("world1");
  37718. attribs.push("world2");
  37719. attribs.push("world3");
  37720. }
  37721. };
  37722. /**
  37723. * Binds the light shadow information to the effect for the given mesh.
  37724. * @param light The light containing the generator
  37725. * @param scene The scene the lights belongs to
  37726. * @param mesh The mesh we are binding the information to render
  37727. * @param lightIndex The light index in the effect used to render the mesh
  37728. * @param effect The effect we are binding the data to
  37729. */
  37730. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  37731. if (light.shadowEnabled && mesh.receiveShadows) {
  37732. var shadowGenerator = light.getShadowGenerator();
  37733. if (shadowGenerator) {
  37734. shadowGenerator.bindShadowLight(lightIndex, effect);
  37735. }
  37736. }
  37737. };
  37738. /**
  37739. * Binds the light information to the effect.
  37740. * @param light The light containing the generator
  37741. * @param effect The effect we are binding the data to
  37742. * @param lightIndex The light index in the effect used to render
  37743. */
  37744. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  37745. light.transferToEffect(effect, lightIndex + "");
  37746. };
  37747. /**
  37748. * Binds the lights information from the scene to the effect for the given mesh.
  37749. * @param scene The scene the lights belongs to
  37750. * @param mesh The mesh we are binding the information to render
  37751. * @param effect The effect we are binding the data to
  37752. * @param defines The generated defines for the effect
  37753. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  37754. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  37755. */
  37756. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  37757. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37758. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  37759. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  37760. for (var i = 0; i < len; i++) {
  37761. var light = mesh._lightSources[i];
  37762. var iAsString = i.toString();
  37763. var scaledIntensity = light.getScaledIntensity();
  37764. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  37765. MaterialHelper.BindLightProperties(light, effect, i);
  37766. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  37767. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  37768. if (defines["SPECULARTERM"]) {
  37769. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  37770. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  37771. }
  37772. // Shadows
  37773. if (scene.shadowsEnabled) {
  37774. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  37775. }
  37776. light._uniformBuffer.update();
  37777. }
  37778. };
  37779. /**
  37780. * Binds the fog information from the scene to the effect for the given mesh.
  37781. * @param scene The scene the lights belongs to
  37782. * @param mesh The mesh we are binding the information to render
  37783. * @param effect The effect we are binding the data to
  37784. */
  37785. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  37786. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  37787. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  37788. effect.setColor3("vFogColor", scene.fogColor);
  37789. }
  37790. };
  37791. /**
  37792. * Binds the bones information from the mesh to the effect.
  37793. * @param mesh The mesh we are binding the information to render
  37794. * @param effect The effect we are binding the data to
  37795. */
  37796. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  37797. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  37798. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  37799. if (matrices && effect) {
  37800. effect.setMatrices("mBones", matrices);
  37801. }
  37802. }
  37803. };
  37804. /**
  37805. * Binds the morph targets information from the mesh to the effect.
  37806. * @param abstractMesh The mesh we are binding the information to render
  37807. * @param effect The effect we are binding the data to
  37808. */
  37809. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  37810. var manager = abstractMesh.morphTargetManager;
  37811. if (!abstractMesh || !manager) {
  37812. return;
  37813. }
  37814. effect.setFloatArray("morphTargetInfluences", manager.influences);
  37815. };
  37816. /**
  37817. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  37818. * @param defines The generated defines used in the effect
  37819. * @param effect The effect we are binding the data to
  37820. * @param scene The scene we are willing to render with logarithmic scale for
  37821. */
  37822. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  37823. if (defines["LOGARITHMICDEPTH"]) {
  37824. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  37825. }
  37826. };
  37827. /**
  37828. * Binds the clip plane information from the scene to the effect.
  37829. * @param scene The scene the clip plane information are extracted from
  37830. * @param effect The effect we are binding the data to
  37831. */
  37832. MaterialHelper.BindClipPlane = function (effect, scene) {
  37833. if (scene.clipPlane) {
  37834. var clipPlane = scene.clipPlane;
  37835. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  37836. }
  37837. };
  37838. return MaterialHelper;
  37839. }());
  37840. BABYLON.MaterialHelper = MaterialHelper;
  37841. })(BABYLON || (BABYLON = {}));
  37842. //# sourceMappingURL=babylon.materialHelper.js.map
  37843. var BABYLON;
  37844. (function (BABYLON) {
  37845. var PushMaterial = /** @class */ (function (_super) {
  37846. __extends(PushMaterial, _super);
  37847. function PushMaterial(name, scene) {
  37848. var _this = _super.call(this, name, scene) || this;
  37849. _this.storeEffectOnSubMeshes = true;
  37850. return _this;
  37851. }
  37852. PushMaterial.prototype.getEffect = function () {
  37853. return this._activeEffect;
  37854. };
  37855. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  37856. if (!mesh) {
  37857. return false;
  37858. }
  37859. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  37860. return true;
  37861. }
  37862. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  37863. };
  37864. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  37865. this._activeEffect.setMatrix("world", world);
  37866. };
  37867. PushMaterial.prototype.bind = function (world, mesh) {
  37868. if (!mesh) {
  37869. return;
  37870. }
  37871. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  37872. };
  37873. PushMaterial.prototype._afterBind = function (mesh, effect) {
  37874. if (effect === void 0) { effect = null; }
  37875. _super.prototype._afterBind.call(this, mesh);
  37876. this.getScene()._cachedEffect = effect;
  37877. };
  37878. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  37879. if (visibility === void 0) { visibility = 1; }
  37880. return scene.isCachedMaterialInvalid(this, effect, visibility);
  37881. };
  37882. return PushMaterial;
  37883. }(BABYLON.Material));
  37884. BABYLON.PushMaterial = PushMaterial;
  37885. })(BABYLON || (BABYLON = {}));
  37886. //# sourceMappingURL=babylon.pushMaterial.js.map
  37887. var BABYLON;
  37888. (function (BABYLON) {
  37889. var StandardMaterialDefines = /** @class */ (function (_super) {
  37890. __extends(StandardMaterialDefines, _super);
  37891. function StandardMaterialDefines() {
  37892. var _this = _super.call(this) || this;
  37893. _this.MAINUV1 = false;
  37894. _this.MAINUV2 = false;
  37895. _this.DIFFUSE = false;
  37896. _this.DIFFUSEDIRECTUV = 0;
  37897. _this.AMBIENT = false;
  37898. _this.AMBIENTDIRECTUV = 0;
  37899. _this.OPACITY = false;
  37900. _this.OPACITYDIRECTUV = 0;
  37901. _this.OPACITYRGB = false;
  37902. _this.REFLECTION = false;
  37903. _this.EMISSIVE = false;
  37904. _this.EMISSIVEDIRECTUV = 0;
  37905. _this.SPECULAR = false;
  37906. _this.SPECULARDIRECTUV = 0;
  37907. _this.BUMP = false;
  37908. _this.BUMPDIRECTUV = 0;
  37909. _this.PARALLAX = false;
  37910. _this.PARALLAXOCCLUSION = false;
  37911. _this.SPECULAROVERALPHA = false;
  37912. _this.CLIPPLANE = false;
  37913. _this.ALPHATEST = false;
  37914. _this.DEPTHPREPASS = false;
  37915. _this.ALPHAFROMDIFFUSE = false;
  37916. _this.POINTSIZE = false;
  37917. _this.FOG = false;
  37918. _this.SPECULARTERM = false;
  37919. _this.DIFFUSEFRESNEL = false;
  37920. _this.OPACITYFRESNEL = false;
  37921. _this.REFLECTIONFRESNEL = false;
  37922. _this.REFRACTIONFRESNEL = false;
  37923. _this.EMISSIVEFRESNEL = false;
  37924. _this.FRESNEL = false;
  37925. _this.NORMAL = false;
  37926. _this.UV1 = false;
  37927. _this.UV2 = false;
  37928. _this.VERTEXCOLOR = false;
  37929. _this.VERTEXALPHA = false;
  37930. _this.NUM_BONE_INFLUENCERS = 0;
  37931. _this.BonesPerMesh = 0;
  37932. _this.INSTANCES = false;
  37933. _this.GLOSSINESS = false;
  37934. _this.ROUGHNESS = false;
  37935. _this.EMISSIVEASILLUMINATION = false;
  37936. _this.LINKEMISSIVEWITHDIFFUSE = false;
  37937. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  37938. _this.LIGHTMAP = false;
  37939. _this.LIGHTMAPDIRECTUV = 0;
  37940. _this.USELIGHTMAPASSHADOWMAP = false;
  37941. _this.REFLECTIONMAP_3D = false;
  37942. _this.REFLECTIONMAP_SPHERICAL = false;
  37943. _this.REFLECTIONMAP_PLANAR = false;
  37944. _this.REFLECTIONMAP_CUBIC = false;
  37945. _this.REFLECTIONMAP_PROJECTION = false;
  37946. _this.REFLECTIONMAP_SKYBOX = false;
  37947. _this.REFLECTIONMAP_EXPLICIT = false;
  37948. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  37949. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  37950. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  37951. _this.INVERTCUBICMAP = false;
  37952. _this.LOGARITHMICDEPTH = false;
  37953. _this.REFRACTION = false;
  37954. _this.REFRACTIONMAP_3D = false;
  37955. _this.REFLECTIONOVERALPHA = false;
  37956. _this.TWOSIDEDLIGHTING = false;
  37957. _this.SHADOWFLOAT = false;
  37958. _this.MORPHTARGETS = false;
  37959. _this.MORPHTARGETS_NORMAL = false;
  37960. _this.MORPHTARGETS_TANGENT = false;
  37961. _this.NUM_MORPH_INFLUENCERS = 0;
  37962. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  37963. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  37964. _this.IMAGEPROCESSING = false;
  37965. _this.VIGNETTE = false;
  37966. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  37967. _this.VIGNETTEBLENDMODEOPAQUE = false;
  37968. _this.TONEMAPPING = false;
  37969. _this.CONTRAST = false;
  37970. _this.COLORCURVES = false;
  37971. _this.COLORGRADING = false;
  37972. _this.COLORGRADING3D = false;
  37973. _this.SAMPLER3DGREENDEPTH = false;
  37974. _this.SAMPLER3DBGRMAP = false;
  37975. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  37976. _this.EXPOSURE = false;
  37977. _this.rebuild();
  37978. return _this;
  37979. }
  37980. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  37981. var modes = [
  37982. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  37983. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  37984. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  37985. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  37986. ];
  37987. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  37988. var mode = modes_1[_i];
  37989. this[mode] = (mode === modeToEnable);
  37990. }
  37991. };
  37992. return StandardMaterialDefines;
  37993. }(BABYLON.MaterialDefines));
  37994. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  37995. var StandardMaterial = /** @class */ (function (_super) {
  37996. __extends(StandardMaterial, _super);
  37997. function StandardMaterial(name, scene) {
  37998. var _this = _super.call(this, name, scene) || this;
  37999. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38000. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  38001. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  38002. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38003. _this.specularPower = 64;
  38004. _this._useAlphaFromDiffuseTexture = false;
  38005. _this._useEmissiveAsIllumination = false;
  38006. _this._linkEmissiveWithDiffuse = false;
  38007. _this._useSpecularOverAlpha = false;
  38008. _this._useReflectionOverAlpha = false;
  38009. _this._disableLighting = false;
  38010. _this._useParallax = false;
  38011. _this._useParallaxOcclusion = false;
  38012. _this.parallaxScaleBias = 0.05;
  38013. _this._roughness = 0;
  38014. _this.indexOfRefraction = 0.98;
  38015. _this.invertRefractionY = true;
  38016. _this._useLightmapAsShadowmap = false;
  38017. _this._useReflectionFresnelFromSpecular = false;
  38018. _this._useGlossinessFromSpecularMapAlpha = false;
  38019. _this._maxSimultaneousLights = 4;
  38020. /**
  38021. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38022. */
  38023. _this._invertNormalMapX = false;
  38024. /**
  38025. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38026. */
  38027. _this._invertNormalMapY = false;
  38028. /**
  38029. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38030. */
  38031. _this._twoSidedLighting = false;
  38032. _this._renderTargets = new BABYLON.SmartArray(16);
  38033. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  38034. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38035. // Setup the default processing configuration to the scene.
  38036. _this._attachImageProcessingConfiguration(null);
  38037. _this.getRenderTargetTextures = function () {
  38038. _this._renderTargets.reset();
  38039. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38040. _this._renderTargets.push(_this._reflectionTexture);
  38041. }
  38042. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38043. _this._renderTargets.push(_this._refractionTexture);
  38044. }
  38045. return _this._renderTargets;
  38046. };
  38047. return _this;
  38048. }
  38049. ;
  38050. ;
  38051. ;
  38052. ;
  38053. ;
  38054. ;
  38055. ;
  38056. ;
  38057. ;
  38058. ;
  38059. ;
  38060. ;
  38061. ;
  38062. ;
  38063. ;
  38064. ;
  38065. ;
  38066. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  38067. /**
  38068. * Gets the image processing configuration used either in this material.
  38069. */
  38070. get: function () {
  38071. return this._imageProcessingConfiguration;
  38072. },
  38073. /**
  38074. * Sets the Default image processing configuration used either in the this material.
  38075. *
  38076. * If sets to null, the scene one is in use.
  38077. */
  38078. set: function (value) {
  38079. this._attachImageProcessingConfiguration(value);
  38080. // Ensure the effect will be rebuilt.
  38081. this._markAllSubMeshesAsTexturesDirty();
  38082. },
  38083. enumerable: true,
  38084. configurable: true
  38085. });
  38086. /**
  38087. * Attaches a new image processing configuration to the Standard Material.
  38088. * @param configuration
  38089. */
  38090. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38091. var _this = this;
  38092. if (configuration === this._imageProcessingConfiguration) {
  38093. return;
  38094. }
  38095. // Detaches observer.
  38096. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38097. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38098. }
  38099. // Pick the scene configuration if needed.
  38100. if (!configuration) {
  38101. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38102. }
  38103. else {
  38104. this._imageProcessingConfiguration = configuration;
  38105. }
  38106. // Attaches observer.
  38107. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38108. _this._markAllSubMeshesAsImageProcessingDirty();
  38109. });
  38110. };
  38111. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  38112. /**
  38113. * Gets wether the color curves effect is enabled.
  38114. */
  38115. get: function () {
  38116. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38117. },
  38118. /**
  38119. * Sets wether the color curves effect is enabled.
  38120. */
  38121. set: function (value) {
  38122. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38123. },
  38124. enumerable: true,
  38125. configurable: true
  38126. });
  38127. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  38128. /**
  38129. * Gets wether the color grading effect is enabled.
  38130. */
  38131. get: function () {
  38132. return this.imageProcessingConfiguration.colorGradingEnabled;
  38133. },
  38134. /**
  38135. * Gets wether the color grading effect is enabled.
  38136. */
  38137. set: function (value) {
  38138. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38139. },
  38140. enumerable: true,
  38141. configurable: true
  38142. });
  38143. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  38144. /**
  38145. * Gets wether tonemapping is enabled or not.
  38146. */
  38147. get: function () {
  38148. return this._imageProcessingConfiguration.toneMappingEnabled;
  38149. },
  38150. /**
  38151. * Sets wether tonemapping is enabled or not
  38152. */
  38153. set: function (value) {
  38154. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38155. },
  38156. enumerable: true,
  38157. configurable: true
  38158. });
  38159. ;
  38160. ;
  38161. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  38162. /**
  38163. * The camera exposure used on this material.
  38164. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38165. * This corresponds to a photographic exposure.
  38166. */
  38167. get: function () {
  38168. return this._imageProcessingConfiguration.exposure;
  38169. },
  38170. /**
  38171. * The camera exposure used on this material.
  38172. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38173. * This corresponds to a photographic exposure.
  38174. */
  38175. set: function (value) {
  38176. this._imageProcessingConfiguration.exposure = value;
  38177. },
  38178. enumerable: true,
  38179. configurable: true
  38180. });
  38181. ;
  38182. ;
  38183. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  38184. /**
  38185. * Gets The camera contrast used on this material.
  38186. */
  38187. get: function () {
  38188. return this._imageProcessingConfiguration.contrast;
  38189. },
  38190. /**
  38191. * Sets The camera contrast used on this material.
  38192. */
  38193. set: function (value) {
  38194. this._imageProcessingConfiguration.contrast = value;
  38195. },
  38196. enumerable: true,
  38197. configurable: true
  38198. });
  38199. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  38200. /**
  38201. * Gets the Color Grading 2D Lookup Texture.
  38202. */
  38203. get: function () {
  38204. return this._imageProcessingConfiguration.colorGradingTexture;
  38205. },
  38206. /**
  38207. * Sets the Color Grading 2D Lookup Texture.
  38208. */
  38209. set: function (value) {
  38210. this._imageProcessingConfiguration.colorGradingTexture = value;
  38211. },
  38212. enumerable: true,
  38213. configurable: true
  38214. });
  38215. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  38216. /**
  38217. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38218. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38219. * 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;
  38220. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38221. */
  38222. get: function () {
  38223. return this._imageProcessingConfiguration.colorCurves;
  38224. },
  38225. /**
  38226. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38227. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38228. * 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;
  38229. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38230. */
  38231. set: function (value) {
  38232. this._imageProcessingConfiguration.colorCurves = value;
  38233. },
  38234. enumerable: true,
  38235. configurable: true
  38236. });
  38237. StandardMaterial.prototype.getClassName = function () {
  38238. return "StandardMaterial";
  38239. };
  38240. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  38241. get: function () {
  38242. return this._useLogarithmicDepth;
  38243. },
  38244. set: function (value) {
  38245. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  38246. this._markAllSubMeshesAsMiscDirty();
  38247. },
  38248. enumerable: true,
  38249. configurable: true
  38250. });
  38251. StandardMaterial.prototype.needAlphaBlending = function () {
  38252. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  38253. };
  38254. StandardMaterial.prototype.needAlphaTesting = function () {
  38255. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  38256. };
  38257. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  38258. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  38259. };
  38260. StandardMaterial.prototype.getAlphaTestTexture = function () {
  38261. return this._diffuseTexture;
  38262. };
  38263. /**
  38264. * Child classes can use it to update shaders
  38265. */
  38266. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  38267. if (useInstances === void 0) { useInstances = false; }
  38268. if (subMesh.effect && this.isFrozen) {
  38269. if (this._wasPreviouslyReady && subMesh.effect) {
  38270. return true;
  38271. }
  38272. }
  38273. if (!subMesh._materialDefines) {
  38274. subMesh._materialDefines = new StandardMaterialDefines();
  38275. }
  38276. var scene = this.getScene();
  38277. var defines = subMesh._materialDefines;
  38278. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  38279. if (defines._renderId === scene.getRenderId()) {
  38280. return true;
  38281. }
  38282. }
  38283. var engine = scene.getEngine();
  38284. // Lights
  38285. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  38286. // Textures
  38287. if (defines._areTexturesDirty) {
  38288. defines._needUVs = false;
  38289. defines.MAINUV1 = false;
  38290. defines.MAINUV2 = false;
  38291. if (scene.texturesEnabled) {
  38292. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  38293. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  38294. return false;
  38295. }
  38296. else {
  38297. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  38298. }
  38299. }
  38300. else {
  38301. defines.DIFFUSE = false;
  38302. }
  38303. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  38304. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38305. return false;
  38306. }
  38307. else {
  38308. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  38309. }
  38310. }
  38311. else {
  38312. defines.AMBIENT = false;
  38313. }
  38314. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  38315. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38316. return false;
  38317. }
  38318. else {
  38319. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  38320. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  38321. }
  38322. }
  38323. else {
  38324. defines.OPACITY = false;
  38325. }
  38326. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  38327. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  38328. return false;
  38329. }
  38330. else {
  38331. defines._needNormals = true;
  38332. defines.REFLECTION = true;
  38333. defines.ROUGHNESS = (this._roughness > 0);
  38334. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  38335. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  38336. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  38337. switch (this._reflectionTexture.coordinatesMode) {
  38338. case BABYLON.Texture.CUBIC_MODE:
  38339. case BABYLON.Texture.INVCUBIC_MODE:
  38340. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  38341. break;
  38342. case BABYLON.Texture.EXPLICIT_MODE:
  38343. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  38344. break;
  38345. case BABYLON.Texture.PLANAR_MODE:
  38346. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  38347. break;
  38348. case BABYLON.Texture.PROJECTION_MODE:
  38349. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  38350. break;
  38351. case BABYLON.Texture.SKYBOX_MODE:
  38352. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  38353. break;
  38354. case BABYLON.Texture.SPHERICAL_MODE:
  38355. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  38356. break;
  38357. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38358. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  38359. break;
  38360. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38361. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  38362. break;
  38363. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38364. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  38365. break;
  38366. }
  38367. }
  38368. }
  38369. else {
  38370. defines.REFLECTION = false;
  38371. }
  38372. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  38373. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38374. return false;
  38375. }
  38376. else {
  38377. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  38378. }
  38379. }
  38380. else {
  38381. defines.EMISSIVE = false;
  38382. }
  38383. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  38384. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38385. return false;
  38386. }
  38387. else {
  38388. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  38389. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38390. }
  38391. }
  38392. else {
  38393. defines.LIGHTMAP = false;
  38394. }
  38395. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  38396. if (!this._specularTexture.isReadyOrNotBlocking()) {
  38397. return false;
  38398. }
  38399. else {
  38400. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  38401. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  38402. }
  38403. }
  38404. else {
  38405. defines.SPECULAR = false;
  38406. }
  38407. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  38408. // Bump texure can not be not blocking.
  38409. if (!this._bumpTexture.isReady()) {
  38410. return false;
  38411. }
  38412. else {
  38413. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  38414. defines.PARALLAX = this._useParallax;
  38415. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  38416. }
  38417. }
  38418. else {
  38419. defines.BUMP = false;
  38420. }
  38421. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  38422. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  38423. return false;
  38424. }
  38425. else {
  38426. defines._needUVs = true;
  38427. defines.REFRACTION = true;
  38428. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  38429. }
  38430. }
  38431. else {
  38432. defines.REFRACTION = false;
  38433. }
  38434. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  38435. }
  38436. else {
  38437. defines.DIFFUSE = false;
  38438. defines.AMBIENT = false;
  38439. defines.OPACITY = false;
  38440. defines.REFLECTION = false;
  38441. defines.EMISSIVE = false;
  38442. defines.LIGHTMAP = false;
  38443. defines.BUMP = false;
  38444. defines.REFRACTION = false;
  38445. }
  38446. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  38447. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  38448. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  38449. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  38450. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  38451. }
  38452. if (defines._areImageProcessingDirty) {
  38453. if (!this._imageProcessingConfiguration.isReady()) {
  38454. return false;
  38455. }
  38456. this._imageProcessingConfiguration.prepareDefines(defines);
  38457. }
  38458. if (defines._areFresnelDirty) {
  38459. if (StandardMaterial.FresnelEnabled) {
  38460. // Fresnel
  38461. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  38462. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  38463. this._reflectionFresnelParameters) {
  38464. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  38465. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  38466. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  38467. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  38468. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  38469. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  38470. defines._needNormals = true;
  38471. defines.FRESNEL = true;
  38472. }
  38473. }
  38474. else {
  38475. defines.FRESNEL = false;
  38476. }
  38477. }
  38478. // Misc.
  38479. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  38480. // Attribs
  38481. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  38482. // Values that need to be evaluated on every frame
  38483. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  38484. // Get correct effect
  38485. if (defines.isDirty) {
  38486. defines.markAsProcessed();
  38487. scene.resetCachedMaterial();
  38488. // Fallbacks
  38489. var fallbacks = new BABYLON.EffectFallbacks();
  38490. if (defines.REFLECTION) {
  38491. fallbacks.addFallback(0, "REFLECTION");
  38492. }
  38493. if (defines.SPECULAR) {
  38494. fallbacks.addFallback(0, "SPECULAR");
  38495. }
  38496. if (defines.BUMP) {
  38497. fallbacks.addFallback(0, "BUMP");
  38498. }
  38499. if (defines.PARALLAX) {
  38500. fallbacks.addFallback(1, "PARALLAX");
  38501. }
  38502. if (defines.PARALLAXOCCLUSION) {
  38503. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  38504. }
  38505. if (defines.SPECULAROVERALPHA) {
  38506. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  38507. }
  38508. if (defines.FOG) {
  38509. fallbacks.addFallback(1, "FOG");
  38510. }
  38511. if (defines.POINTSIZE) {
  38512. fallbacks.addFallback(0, "POINTSIZE");
  38513. }
  38514. if (defines.LOGARITHMICDEPTH) {
  38515. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  38516. }
  38517. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  38518. if (defines.SPECULARTERM) {
  38519. fallbacks.addFallback(0, "SPECULARTERM");
  38520. }
  38521. if (defines.DIFFUSEFRESNEL) {
  38522. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  38523. }
  38524. if (defines.OPACITYFRESNEL) {
  38525. fallbacks.addFallback(2, "OPACITYFRESNEL");
  38526. }
  38527. if (defines.REFLECTIONFRESNEL) {
  38528. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  38529. }
  38530. if (defines.EMISSIVEFRESNEL) {
  38531. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  38532. }
  38533. if (defines.FRESNEL) {
  38534. fallbacks.addFallback(4, "FRESNEL");
  38535. }
  38536. //Attributes
  38537. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38538. if (defines.NORMAL) {
  38539. attribs.push(BABYLON.VertexBuffer.NormalKind);
  38540. }
  38541. if (defines.UV1) {
  38542. attribs.push(BABYLON.VertexBuffer.UVKind);
  38543. }
  38544. if (defines.UV2) {
  38545. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38546. }
  38547. if (defines.VERTEXCOLOR) {
  38548. attribs.push(BABYLON.VertexBuffer.ColorKind);
  38549. }
  38550. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  38551. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  38552. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  38553. var shaderName = "default";
  38554. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  38555. "vFogInfos", "vFogColor", "pointSize",
  38556. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  38557. "mBones",
  38558. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  38559. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  38560. "logarithmicDepthConstant", "vTangentSpaceParams"
  38561. ];
  38562. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  38563. var uniformBuffers = ["Material", "Scene"];
  38564. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  38565. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  38566. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  38567. uniformsNames: uniforms,
  38568. uniformBuffersNames: uniformBuffers,
  38569. samplers: samplers,
  38570. defines: defines,
  38571. maxSimultaneousLights: this._maxSimultaneousLights
  38572. });
  38573. if (this.customShaderNameResolve) {
  38574. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  38575. }
  38576. var join = defines.toString();
  38577. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  38578. attributes: attribs,
  38579. uniformsNames: uniforms,
  38580. uniformBuffersNames: uniformBuffers,
  38581. samplers: samplers,
  38582. defines: join,
  38583. fallbacks: fallbacks,
  38584. onCompiled: this.onCompiled,
  38585. onError: this.onError,
  38586. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  38587. }, engine), defines);
  38588. this.buildUniformLayout();
  38589. }
  38590. if (!subMesh.effect || !subMesh.effect.isReady()) {
  38591. return false;
  38592. }
  38593. defines._renderId = scene.getRenderId();
  38594. this._wasPreviouslyReady = true;
  38595. return true;
  38596. };
  38597. StandardMaterial.prototype.buildUniformLayout = function () {
  38598. // Order is important !
  38599. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  38600. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  38601. this._uniformBuffer.addUniform("opacityParts", 4);
  38602. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  38603. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  38604. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  38605. this._uniformBuffer.addUniform("refractionRightColor", 4);
  38606. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  38607. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  38608. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  38609. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  38610. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  38611. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  38612. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  38613. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  38614. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  38615. this._uniformBuffer.addUniform("vBumpInfos", 3);
  38616. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  38617. this._uniformBuffer.addUniform("ambientMatrix", 16);
  38618. this._uniformBuffer.addUniform("opacityMatrix", 16);
  38619. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  38620. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  38621. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  38622. this._uniformBuffer.addUniform("specularMatrix", 16);
  38623. this._uniformBuffer.addUniform("bumpMatrix", 16);
  38624. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  38625. this._uniformBuffer.addUniform("refractionMatrix", 16);
  38626. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  38627. this._uniformBuffer.addUniform("vSpecularColor", 4);
  38628. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  38629. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  38630. this._uniformBuffer.addUniform("pointSize", 1);
  38631. this._uniformBuffer.create();
  38632. };
  38633. StandardMaterial.prototype.unbind = function () {
  38634. if (this._activeEffect) {
  38635. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  38636. this._activeEffect.setTexture("reflection2DSampler", null);
  38637. }
  38638. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  38639. this._activeEffect.setTexture("refraction2DSampler", null);
  38640. }
  38641. }
  38642. _super.prototype.unbind.call(this);
  38643. };
  38644. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  38645. var scene = this.getScene();
  38646. var defines = subMesh._materialDefines;
  38647. if (!defines) {
  38648. return;
  38649. }
  38650. var effect = subMesh.effect;
  38651. if (!effect) {
  38652. return;
  38653. }
  38654. this._activeEffect = effect;
  38655. // Matrices
  38656. this.bindOnlyWorldMatrix(world);
  38657. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  38658. // Bones
  38659. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  38660. if (mustRebind) {
  38661. this._uniformBuffer.bindToEffect(effect, "Material");
  38662. this.bindViewProjection(effect);
  38663. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  38664. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  38665. // Fresnel
  38666. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  38667. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  38668. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  38669. }
  38670. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  38671. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  38672. }
  38673. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  38674. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  38675. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  38676. }
  38677. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  38678. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  38679. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  38680. }
  38681. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  38682. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  38683. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  38684. }
  38685. }
  38686. // Textures
  38687. if (scene.texturesEnabled) {
  38688. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  38689. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  38690. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  38691. }
  38692. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  38693. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  38694. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  38695. }
  38696. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  38697. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  38698. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  38699. }
  38700. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  38701. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  38702. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  38703. }
  38704. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  38705. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  38706. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  38707. }
  38708. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  38709. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  38710. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  38711. }
  38712. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  38713. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  38714. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  38715. }
  38716. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  38717. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  38718. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  38719. if (scene._mirroredCameraPosition) {
  38720. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  38721. }
  38722. else {
  38723. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  38724. }
  38725. }
  38726. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  38727. var depth = 1.0;
  38728. if (!this._refractionTexture.isCube) {
  38729. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  38730. if (this._refractionTexture.depth) {
  38731. depth = this._refractionTexture.depth;
  38732. }
  38733. }
  38734. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  38735. }
  38736. }
  38737. // Point size
  38738. if (this.pointsCloud) {
  38739. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  38740. }
  38741. if (defines.SPECULARTERM) {
  38742. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  38743. }
  38744. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  38745. // Diffuse
  38746. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  38747. }
  38748. // Textures
  38749. if (scene.texturesEnabled) {
  38750. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  38751. effect.setTexture("diffuseSampler", this._diffuseTexture);
  38752. }
  38753. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  38754. effect.setTexture("ambientSampler", this._ambientTexture);
  38755. }
  38756. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  38757. effect.setTexture("opacitySampler", this._opacityTexture);
  38758. }
  38759. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  38760. if (this._reflectionTexture.isCube) {
  38761. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  38762. }
  38763. else {
  38764. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  38765. }
  38766. }
  38767. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  38768. effect.setTexture("emissiveSampler", this._emissiveTexture);
  38769. }
  38770. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  38771. effect.setTexture("lightmapSampler", this._lightmapTexture);
  38772. }
  38773. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  38774. effect.setTexture("specularSampler", this._specularTexture);
  38775. }
  38776. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  38777. effect.setTexture("bumpSampler", this._bumpTexture);
  38778. }
  38779. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  38780. var depth = 1.0;
  38781. if (this._refractionTexture.isCube) {
  38782. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  38783. }
  38784. else {
  38785. effect.setTexture("refraction2DSampler", this._refractionTexture);
  38786. }
  38787. }
  38788. }
  38789. // Clip plane
  38790. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  38791. // Colors
  38792. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  38793. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  38794. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  38795. }
  38796. if (mustRebind || !this.isFrozen) {
  38797. // Lights
  38798. if (scene.lightsEnabled && !this._disableLighting) {
  38799. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  38800. }
  38801. // View
  38802. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  38803. this.bindView(effect);
  38804. }
  38805. // Fog
  38806. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  38807. // Morph targets
  38808. if (defines.NUM_MORPH_INFLUENCERS) {
  38809. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  38810. }
  38811. // Log. depth
  38812. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  38813. // image processing
  38814. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  38815. this._imageProcessingConfiguration.bind(this._activeEffect);
  38816. }
  38817. }
  38818. this._uniformBuffer.update();
  38819. this._afterBind(mesh, this._activeEffect);
  38820. };
  38821. StandardMaterial.prototype.getAnimatables = function () {
  38822. var results = [];
  38823. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  38824. results.push(this._diffuseTexture);
  38825. }
  38826. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  38827. results.push(this._ambientTexture);
  38828. }
  38829. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  38830. results.push(this._opacityTexture);
  38831. }
  38832. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  38833. results.push(this._reflectionTexture);
  38834. }
  38835. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  38836. results.push(this._emissiveTexture);
  38837. }
  38838. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  38839. results.push(this._specularTexture);
  38840. }
  38841. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  38842. results.push(this._bumpTexture);
  38843. }
  38844. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  38845. results.push(this._lightmapTexture);
  38846. }
  38847. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  38848. results.push(this._refractionTexture);
  38849. }
  38850. return results;
  38851. };
  38852. StandardMaterial.prototype.getActiveTextures = function () {
  38853. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38854. if (this._diffuseTexture) {
  38855. activeTextures.push(this._diffuseTexture);
  38856. }
  38857. if (this._ambientTexture) {
  38858. activeTextures.push(this._ambientTexture);
  38859. }
  38860. if (this._opacityTexture) {
  38861. activeTextures.push(this._opacityTexture);
  38862. }
  38863. if (this._reflectionTexture) {
  38864. activeTextures.push(this._reflectionTexture);
  38865. }
  38866. if (this._emissiveTexture) {
  38867. activeTextures.push(this._emissiveTexture);
  38868. }
  38869. if (this._specularTexture) {
  38870. activeTextures.push(this._specularTexture);
  38871. }
  38872. if (this._bumpTexture) {
  38873. activeTextures.push(this._bumpTexture);
  38874. }
  38875. if (this._lightmapTexture) {
  38876. activeTextures.push(this._lightmapTexture);
  38877. }
  38878. if (this._refractionTexture) {
  38879. activeTextures.push(this._refractionTexture);
  38880. }
  38881. return activeTextures;
  38882. };
  38883. StandardMaterial.prototype.hasTexture = function (texture) {
  38884. if (_super.prototype.hasTexture.call(this, texture)) {
  38885. return true;
  38886. }
  38887. if (this._diffuseTexture === texture) {
  38888. return true;
  38889. }
  38890. if (this._ambientTexture === texture) {
  38891. return true;
  38892. }
  38893. if (this._opacityTexture === texture) {
  38894. return true;
  38895. }
  38896. if (this._reflectionTexture === texture) {
  38897. return true;
  38898. }
  38899. if (this._emissiveTexture === texture) {
  38900. return true;
  38901. }
  38902. if (this._specularTexture === texture) {
  38903. return true;
  38904. }
  38905. if (this._bumpTexture === texture) {
  38906. return true;
  38907. }
  38908. if (this._lightmapTexture === texture) {
  38909. return true;
  38910. }
  38911. if (this._refractionTexture === texture) {
  38912. return true;
  38913. }
  38914. return false;
  38915. };
  38916. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  38917. if (forceDisposeTextures) {
  38918. if (this._diffuseTexture) {
  38919. this._diffuseTexture.dispose();
  38920. }
  38921. if (this._ambientTexture) {
  38922. this._ambientTexture.dispose();
  38923. }
  38924. if (this._opacityTexture) {
  38925. this._opacityTexture.dispose();
  38926. }
  38927. if (this._reflectionTexture) {
  38928. this._reflectionTexture.dispose();
  38929. }
  38930. if (this._emissiveTexture) {
  38931. this._emissiveTexture.dispose();
  38932. }
  38933. if (this._specularTexture) {
  38934. this._specularTexture.dispose();
  38935. }
  38936. if (this._bumpTexture) {
  38937. this._bumpTexture.dispose();
  38938. }
  38939. if (this._lightmapTexture) {
  38940. this._lightmapTexture.dispose();
  38941. }
  38942. if (this._refractionTexture) {
  38943. this._refractionTexture.dispose();
  38944. }
  38945. }
  38946. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38947. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38948. }
  38949. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  38950. };
  38951. StandardMaterial.prototype.clone = function (name) {
  38952. var _this = this;
  38953. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  38954. result.name = name;
  38955. result.id = name;
  38956. return result;
  38957. };
  38958. StandardMaterial.prototype.serialize = function () {
  38959. return BABYLON.SerializationHelper.Serialize(this);
  38960. };
  38961. // Statics
  38962. StandardMaterial.Parse = function (source, scene, rootUrl) {
  38963. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  38964. };
  38965. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  38966. get: function () {
  38967. return StandardMaterial._DiffuseTextureEnabled;
  38968. },
  38969. set: function (value) {
  38970. if (StandardMaterial._DiffuseTextureEnabled === value) {
  38971. return;
  38972. }
  38973. StandardMaterial._DiffuseTextureEnabled = value;
  38974. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  38975. },
  38976. enumerable: true,
  38977. configurable: true
  38978. });
  38979. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  38980. get: function () {
  38981. return StandardMaterial._AmbientTextureEnabled;
  38982. },
  38983. set: function (value) {
  38984. if (StandardMaterial._AmbientTextureEnabled === value) {
  38985. return;
  38986. }
  38987. StandardMaterial._AmbientTextureEnabled = value;
  38988. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  38989. },
  38990. enumerable: true,
  38991. configurable: true
  38992. });
  38993. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  38994. get: function () {
  38995. return StandardMaterial._OpacityTextureEnabled;
  38996. },
  38997. set: function (value) {
  38998. if (StandardMaterial._OpacityTextureEnabled === value) {
  38999. return;
  39000. }
  39001. StandardMaterial._OpacityTextureEnabled = value;
  39002. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39003. },
  39004. enumerable: true,
  39005. configurable: true
  39006. });
  39007. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  39008. get: function () {
  39009. return StandardMaterial._ReflectionTextureEnabled;
  39010. },
  39011. set: function (value) {
  39012. if (StandardMaterial._ReflectionTextureEnabled === value) {
  39013. return;
  39014. }
  39015. StandardMaterial._ReflectionTextureEnabled = value;
  39016. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39017. },
  39018. enumerable: true,
  39019. configurable: true
  39020. });
  39021. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  39022. get: function () {
  39023. return StandardMaterial._EmissiveTextureEnabled;
  39024. },
  39025. set: function (value) {
  39026. if (StandardMaterial._EmissiveTextureEnabled === value) {
  39027. return;
  39028. }
  39029. StandardMaterial._EmissiveTextureEnabled = value;
  39030. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39031. },
  39032. enumerable: true,
  39033. configurable: true
  39034. });
  39035. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  39036. get: function () {
  39037. return StandardMaterial._SpecularTextureEnabled;
  39038. },
  39039. set: function (value) {
  39040. if (StandardMaterial._SpecularTextureEnabled === value) {
  39041. return;
  39042. }
  39043. StandardMaterial._SpecularTextureEnabled = value;
  39044. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39045. },
  39046. enumerable: true,
  39047. configurable: true
  39048. });
  39049. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  39050. get: function () {
  39051. return StandardMaterial._BumpTextureEnabled;
  39052. },
  39053. set: function (value) {
  39054. if (StandardMaterial._BumpTextureEnabled === value) {
  39055. return;
  39056. }
  39057. StandardMaterial._BumpTextureEnabled = value;
  39058. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39059. },
  39060. enumerable: true,
  39061. configurable: true
  39062. });
  39063. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  39064. get: function () {
  39065. return StandardMaterial._LightmapTextureEnabled;
  39066. },
  39067. set: function (value) {
  39068. if (StandardMaterial._LightmapTextureEnabled === value) {
  39069. return;
  39070. }
  39071. StandardMaterial._LightmapTextureEnabled = value;
  39072. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39073. },
  39074. enumerable: true,
  39075. configurable: true
  39076. });
  39077. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  39078. get: function () {
  39079. return StandardMaterial._RefractionTextureEnabled;
  39080. },
  39081. set: function (value) {
  39082. if (StandardMaterial._RefractionTextureEnabled === value) {
  39083. return;
  39084. }
  39085. StandardMaterial._RefractionTextureEnabled = value;
  39086. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39087. },
  39088. enumerable: true,
  39089. configurable: true
  39090. });
  39091. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  39092. get: function () {
  39093. return StandardMaterial._ColorGradingTextureEnabled;
  39094. },
  39095. set: function (value) {
  39096. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  39097. return;
  39098. }
  39099. StandardMaterial._ColorGradingTextureEnabled = value;
  39100. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39101. },
  39102. enumerable: true,
  39103. configurable: true
  39104. });
  39105. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  39106. get: function () {
  39107. return StandardMaterial._FresnelEnabled;
  39108. },
  39109. set: function (value) {
  39110. if (StandardMaterial._FresnelEnabled === value) {
  39111. return;
  39112. }
  39113. StandardMaterial._FresnelEnabled = value;
  39114. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  39115. },
  39116. enumerable: true,
  39117. configurable: true
  39118. });
  39119. // Flags used to enable or disable a type of texture for all Standard Materials
  39120. StandardMaterial._DiffuseTextureEnabled = true;
  39121. StandardMaterial._AmbientTextureEnabled = true;
  39122. StandardMaterial._OpacityTextureEnabled = true;
  39123. StandardMaterial._ReflectionTextureEnabled = true;
  39124. StandardMaterial._EmissiveTextureEnabled = true;
  39125. StandardMaterial._SpecularTextureEnabled = true;
  39126. StandardMaterial._BumpTextureEnabled = true;
  39127. StandardMaterial._LightmapTextureEnabled = true;
  39128. StandardMaterial._RefractionTextureEnabled = true;
  39129. StandardMaterial._ColorGradingTextureEnabled = true;
  39130. StandardMaterial._FresnelEnabled = true;
  39131. __decorate([
  39132. BABYLON.serializeAsTexture("diffuseTexture")
  39133. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  39134. __decorate([
  39135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39136. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  39137. __decorate([
  39138. BABYLON.serializeAsTexture("ambientTexture")
  39139. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  39140. __decorate([
  39141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39142. ], StandardMaterial.prototype, "ambientTexture", void 0);
  39143. __decorate([
  39144. BABYLON.serializeAsTexture("opacityTexture")
  39145. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  39146. __decorate([
  39147. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39148. ], StandardMaterial.prototype, "opacityTexture", void 0);
  39149. __decorate([
  39150. BABYLON.serializeAsTexture("reflectionTexture")
  39151. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  39152. __decorate([
  39153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39154. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  39155. __decorate([
  39156. BABYLON.serializeAsTexture("emissiveTexture")
  39157. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  39158. __decorate([
  39159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39160. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  39161. __decorate([
  39162. BABYLON.serializeAsTexture("specularTexture")
  39163. ], StandardMaterial.prototype, "_specularTexture", void 0);
  39164. __decorate([
  39165. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39166. ], StandardMaterial.prototype, "specularTexture", void 0);
  39167. __decorate([
  39168. BABYLON.serializeAsTexture("bumpTexture")
  39169. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  39170. __decorate([
  39171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39172. ], StandardMaterial.prototype, "bumpTexture", void 0);
  39173. __decorate([
  39174. BABYLON.serializeAsTexture("lightmapTexture")
  39175. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  39176. __decorate([
  39177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39178. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  39179. __decorate([
  39180. BABYLON.serializeAsTexture("refractionTexture")
  39181. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  39182. __decorate([
  39183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39184. ], StandardMaterial.prototype, "refractionTexture", void 0);
  39185. __decorate([
  39186. BABYLON.serializeAsColor3("ambient")
  39187. ], StandardMaterial.prototype, "ambientColor", void 0);
  39188. __decorate([
  39189. BABYLON.serializeAsColor3("diffuse")
  39190. ], StandardMaterial.prototype, "diffuseColor", void 0);
  39191. __decorate([
  39192. BABYLON.serializeAsColor3("specular")
  39193. ], StandardMaterial.prototype, "specularColor", void 0);
  39194. __decorate([
  39195. BABYLON.serializeAsColor3("emissive")
  39196. ], StandardMaterial.prototype, "emissiveColor", void 0);
  39197. __decorate([
  39198. BABYLON.serialize()
  39199. ], StandardMaterial.prototype, "specularPower", void 0);
  39200. __decorate([
  39201. BABYLON.serialize("useAlphaFromDiffuseTexture")
  39202. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  39203. __decorate([
  39204. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39205. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  39206. __decorate([
  39207. BABYLON.serialize("useEmissiveAsIllumination")
  39208. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  39209. __decorate([
  39210. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39211. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  39212. __decorate([
  39213. BABYLON.serialize("linkEmissiveWithDiffuse")
  39214. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  39215. __decorate([
  39216. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39217. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  39218. __decorate([
  39219. BABYLON.serialize("useSpecularOverAlpha")
  39220. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  39221. __decorate([
  39222. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39223. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  39224. __decorate([
  39225. BABYLON.serialize("useReflectionOverAlpha")
  39226. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  39227. __decorate([
  39228. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39229. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  39230. __decorate([
  39231. BABYLON.serialize("disableLighting")
  39232. ], StandardMaterial.prototype, "_disableLighting", void 0);
  39233. __decorate([
  39234. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39235. ], StandardMaterial.prototype, "disableLighting", void 0);
  39236. __decorate([
  39237. BABYLON.serialize("useParallax")
  39238. ], StandardMaterial.prototype, "_useParallax", void 0);
  39239. __decorate([
  39240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39241. ], StandardMaterial.prototype, "useParallax", void 0);
  39242. __decorate([
  39243. BABYLON.serialize("useParallaxOcclusion")
  39244. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  39245. __decorate([
  39246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39247. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  39248. __decorate([
  39249. BABYLON.serialize()
  39250. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  39251. __decorate([
  39252. BABYLON.serialize("roughness")
  39253. ], StandardMaterial.prototype, "_roughness", void 0);
  39254. __decorate([
  39255. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39256. ], StandardMaterial.prototype, "roughness", void 0);
  39257. __decorate([
  39258. BABYLON.serialize()
  39259. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  39260. __decorate([
  39261. BABYLON.serialize()
  39262. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  39263. __decorate([
  39264. BABYLON.serialize("useLightmapAsShadowmap")
  39265. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  39266. __decorate([
  39267. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39268. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39269. __decorate([
  39270. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  39271. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  39272. __decorate([
  39273. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39274. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  39275. __decorate([
  39276. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  39277. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  39278. __decorate([
  39279. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  39280. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  39281. __decorate([
  39282. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  39283. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  39284. __decorate([
  39285. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39286. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  39287. __decorate([
  39288. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  39289. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  39290. __decorate([
  39291. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39292. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  39293. __decorate([
  39294. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  39295. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  39296. __decorate([
  39297. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39298. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  39299. __decorate([
  39300. BABYLON.serialize("useReflectionFresnelFromSpecular")
  39301. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  39302. __decorate([
  39303. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39304. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  39305. __decorate([
  39306. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  39307. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  39308. __decorate([
  39309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39310. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  39311. __decorate([
  39312. BABYLON.serialize("maxSimultaneousLights")
  39313. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  39314. __decorate([
  39315. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39316. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  39317. __decorate([
  39318. BABYLON.serialize("invertNormalMapX")
  39319. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  39320. __decorate([
  39321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39322. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  39323. __decorate([
  39324. BABYLON.serialize("invertNormalMapY")
  39325. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  39326. __decorate([
  39327. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39328. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  39329. __decorate([
  39330. BABYLON.serialize("twoSidedLighting")
  39331. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  39332. __decorate([
  39333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39334. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  39335. __decorate([
  39336. BABYLON.serialize()
  39337. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  39338. return StandardMaterial;
  39339. }(BABYLON.PushMaterial));
  39340. BABYLON.StandardMaterial = StandardMaterial;
  39341. })(BABYLON || (BABYLON = {}));
  39342. //# sourceMappingURL=babylon.standardMaterial.js.map
  39343. var BABYLON;
  39344. (function (BABYLON) {
  39345. /**
  39346. * Manages the defines for the PBR Material.
  39347. */
  39348. var PBRMaterialDefines = /** @class */ (function (_super) {
  39349. __extends(PBRMaterialDefines, _super);
  39350. /**
  39351. * Initializes the PBR Material defines.
  39352. */
  39353. function PBRMaterialDefines() {
  39354. var _this = _super.call(this) || this;
  39355. _this.PBR = true;
  39356. _this.MAINUV1 = false;
  39357. _this.MAINUV2 = false;
  39358. _this.UV1 = false;
  39359. _this.UV2 = false;
  39360. _this.ALBEDO = false;
  39361. _this.ALBEDODIRECTUV = 0;
  39362. _this.VERTEXCOLOR = false;
  39363. _this.AMBIENT = false;
  39364. _this.AMBIENTDIRECTUV = 0;
  39365. _this.AMBIENTINGRAYSCALE = false;
  39366. _this.OPACITY = false;
  39367. _this.VERTEXALPHA = false;
  39368. _this.OPACITYDIRECTUV = 0;
  39369. _this.OPACITYRGB = false;
  39370. _this.ALPHATEST = false;
  39371. _this.DEPTHPREPASS = false;
  39372. _this.ALPHABLEND = false;
  39373. _this.ALPHAFROMALBEDO = false;
  39374. _this.ALPHATESTVALUE = 0.5;
  39375. _this.SPECULAROVERALPHA = false;
  39376. _this.RADIANCEOVERALPHA = false;
  39377. _this.ALPHAFRESNEL = false;
  39378. _this.LINEARALPHAFRESNEL = false;
  39379. _this.PREMULTIPLYALPHA = false;
  39380. _this.EMISSIVE = false;
  39381. _this.EMISSIVEDIRECTUV = 0;
  39382. _this.REFLECTIVITY = false;
  39383. _this.REFLECTIVITYDIRECTUV = 0;
  39384. _this.SPECULARTERM = false;
  39385. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  39386. _this.MICROSURFACEAUTOMATIC = false;
  39387. _this.LODBASEDMICROSFURACE = false;
  39388. _this.MICROSURFACEMAP = false;
  39389. _this.MICROSURFACEMAPDIRECTUV = 0;
  39390. _this.METALLICWORKFLOW = false;
  39391. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  39392. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  39393. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  39394. _this.AOSTOREINMETALMAPRED = false;
  39395. _this.ENVIRONMENTBRDF = false;
  39396. _this.NORMAL = false;
  39397. _this.TANGENT = false;
  39398. _this.BUMP = false;
  39399. _this.BUMPDIRECTUV = 0;
  39400. _this.PARALLAX = false;
  39401. _this.PARALLAXOCCLUSION = false;
  39402. _this.NORMALXYSCALE = true;
  39403. _this.LIGHTMAP = false;
  39404. _this.LIGHTMAPDIRECTUV = 0;
  39405. _this.USELIGHTMAPASSHADOWMAP = false;
  39406. _this.REFLECTION = false;
  39407. _this.REFLECTIONMAP_3D = false;
  39408. _this.REFLECTIONMAP_SPHERICAL = false;
  39409. _this.REFLECTIONMAP_PLANAR = false;
  39410. _this.REFLECTIONMAP_CUBIC = false;
  39411. _this.REFLECTIONMAP_PROJECTION = false;
  39412. _this.REFLECTIONMAP_SKYBOX = false;
  39413. _this.REFLECTIONMAP_EXPLICIT = false;
  39414. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39415. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39416. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39417. _this.INVERTCUBICMAP = false;
  39418. _this.USESPHERICALFROMREFLECTIONMAP = false;
  39419. _this.USESPHERICALINVERTEX = false;
  39420. _this.REFLECTIONMAP_OPPOSITEZ = false;
  39421. _this.LODINREFLECTIONALPHA = false;
  39422. _this.GAMMAREFLECTION = false;
  39423. _this.RADIANCEOCCLUSION = false;
  39424. _this.HORIZONOCCLUSION = false;
  39425. _this.REFRACTION = false;
  39426. _this.REFRACTIONMAP_3D = false;
  39427. _this.REFRACTIONMAP_OPPOSITEZ = false;
  39428. _this.LODINREFRACTIONALPHA = false;
  39429. _this.GAMMAREFRACTION = false;
  39430. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  39431. _this.INSTANCES = false;
  39432. _this.NUM_BONE_INFLUENCERS = 0;
  39433. _this.BonesPerMesh = 0;
  39434. _this.NONUNIFORMSCALING = false;
  39435. _this.MORPHTARGETS = false;
  39436. _this.MORPHTARGETS_NORMAL = false;
  39437. _this.MORPHTARGETS_TANGENT = false;
  39438. _this.NUM_MORPH_INFLUENCERS = 0;
  39439. _this.IMAGEPROCESSING = false;
  39440. _this.VIGNETTE = false;
  39441. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39442. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39443. _this.TONEMAPPING = false;
  39444. _this.CONTRAST = false;
  39445. _this.COLORCURVES = false;
  39446. _this.COLORGRADING = false;
  39447. _this.COLORGRADING3D = false;
  39448. _this.SAMPLER3DGREENDEPTH = false;
  39449. _this.SAMPLER3DBGRMAP = false;
  39450. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39451. _this.EXPOSURE = false;
  39452. _this.USEPHYSICALLIGHTFALLOFF = false;
  39453. _this.TWOSIDEDLIGHTING = false;
  39454. _this.SHADOWFLOAT = false;
  39455. _this.CLIPPLANE = false;
  39456. _this.POINTSIZE = false;
  39457. _this.FOG = false;
  39458. _this.LOGARITHMICDEPTH = false;
  39459. _this.FORCENORMALFORWARD = false;
  39460. _this.rebuild();
  39461. return _this;
  39462. }
  39463. /**
  39464. * Resets the PBR Material defines.
  39465. */
  39466. PBRMaterialDefines.prototype.reset = function () {
  39467. _super.prototype.reset.call(this);
  39468. this.ALPHATESTVALUE = 0.5;
  39469. this.PBR = true;
  39470. };
  39471. return PBRMaterialDefines;
  39472. }(BABYLON.MaterialDefines));
  39473. /**
  39474. * The Physically based material base class of BJS.
  39475. *
  39476. * This offers the main features of a standard PBR material.
  39477. * For more information, please refer to the documentation :
  39478. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  39479. */
  39480. var PBRBaseMaterial = /** @class */ (function (_super) {
  39481. __extends(PBRBaseMaterial, _super);
  39482. /**
  39483. * Instantiates a new PBRMaterial instance.
  39484. *
  39485. * @param name The material name
  39486. * @param scene The scene the material will be use in.
  39487. */
  39488. function PBRBaseMaterial(name, scene) {
  39489. var _this = _super.call(this, name, scene) || this;
  39490. /**
  39491. * Intensity of the direct lights e.g. the four lights available in your scene.
  39492. * This impacts both the direct diffuse and specular highlights.
  39493. */
  39494. _this._directIntensity = 1.0;
  39495. /**
  39496. * Intensity of the emissive part of the material.
  39497. * This helps controlling the emissive effect without modifying the emissive color.
  39498. */
  39499. _this._emissiveIntensity = 1.0;
  39500. /**
  39501. * Intensity of the environment e.g. how much the environment will light the object
  39502. * either through harmonics for rough material or through the refelction for shiny ones.
  39503. */
  39504. _this._environmentIntensity = 1.0;
  39505. /**
  39506. * This is a special control allowing the reduction of the specular highlights coming from the
  39507. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  39508. */
  39509. _this._specularIntensity = 1.0;
  39510. /**
  39511. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  39512. */
  39513. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  39514. /**
  39515. * Debug Control allowing disabling the bump map on this material.
  39516. */
  39517. _this._disableBumpMap = false;
  39518. /**
  39519. * AKA Occlusion Texture Intensity in other nomenclature.
  39520. */
  39521. _this._ambientTextureStrength = 1.0;
  39522. /**
  39523. * The color of a material in ambient lighting.
  39524. */
  39525. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  39526. /**
  39527. * AKA Diffuse Color in other nomenclature.
  39528. */
  39529. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  39530. /**
  39531. * AKA Specular Color in other nomenclature.
  39532. */
  39533. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  39534. /**
  39535. * The color applied when light is reflected from a material.
  39536. */
  39537. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  39538. /**
  39539. * The color applied when light is emitted from a material.
  39540. */
  39541. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  39542. /**
  39543. * AKA Glossiness in other nomenclature.
  39544. */
  39545. _this._microSurface = 0.9;
  39546. /**
  39547. * source material index of refraction (IOR)' / 'destination material IOR.
  39548. */
  39549. _this._indexOfRefraction = 0.66;
  39550. /**
  39551. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  39552. */
  39553. _this._invertRefractionY = false;
  39554. /**
  39555. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  39556. * Materials half opaque for instance using refraction could benefit from this control.
  39557. */
  39558. _this._linkRefractionWithTransparency = false;
  39559. /**
  39560. * Specifies that the material will use the light map as a show map.
  39561. */
  39562. _this._useLightmapAsShadowmap = false;
  39563. /**
  39564. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  39565. * makes the reflect vector face the model (under horizon).
  39566. */
  39567. _this._useHorizonOcclusion = true;
  39568. /**
  39569. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  39570. * too much the area relying on ambient texture to define their ambient occlusion.
  39571. */
  39572. _this._useRadianceOcclusion = true;
  39573. /**
  39574. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  39575. */
  39576. _this._useAlphaFromAlbedoTexture = false;
  39577. /**
  39578. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  39579. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  39580. */
  39581. _this._useSpecularOverAlpha = true;
  39582. /**
  39583. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  39584. */
  39585. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  39586. /**
  39587. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  39588. */
  39589. _this._useRoughnessFromMetallicTextureAlpha = true;
  39590. /**
  39591. * Specifies if the metallic texture contains the roughness information in its green channel.
  39592. */
  39593. _this._useRoughnessFromMetallicTextureGreen = false;
  39594. /**
  39595. * Specifies if the metallic texture contains the metallness information in its blue channel.
  39596. */
  39597. _this._useMetallnessFromMetallicTextureBlue = false;
  39598. /**
  39599. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  39600. */
  39601. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  39602. /**
  39603. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  39604. */
  39605. _this._useAmbientInGrayScale = false;
  39606. /**
  39607. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  39608. * The material will try to infer what glossiness each pixel should be.
  39609. */
  39610. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  39611. /**
  39612. * BJS is using an harcoded light falloff based on a manually sets up range.
  39613. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  39614. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  39615. */
  39616. _this._usePhysicalLightFalloff = true;
  39617. /**
  39618. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  39619. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  39620. */
  39621. _this._useRadianceOverAlpha = true;
  39622. /**
  39623. * Allows using the bump map in parallax mode.
  39624. */
  39625. _this._useParallax = false;
  39626. /**
  39627. * Allows using the bump map in parallax occlusion mode.
  39628. */
  39629. _this._useParallaxOcclusion = false;
  39630. /**
  39631. * Controls the scale bias of the parallax mode.
  39632. */
  39633. _this._parallaxScaleBias = 0.05;
  39634. /**
  39635. * If sets to true, disables all the lights affecting the material.
  39636. */
  39637. _this._disableLighting = false;
  39638. /**
  39639. * Number of Simultaneous lights allowed on the material.
  39640. */
  39641. _this._maxSimultaneousLights = 4;
  39642. /**
  39643. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  39644. */
  39645. _this._invertNormalMapX = false;
  39646. /**
  39647. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  39648. */
  39649. _this._invertNormalMapY = false;
  39650. /**
  39651. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39652. */
  39653. _this._twoSidedLighting = false;
  39654. /**
  39655. * Defines the alpha limits in alpha test mode.
  39656. */
  39657. _this._alphaCutOff = 0.4;
  39658. /**
  39659. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  39660. */
  39661. _this._forceAlphaTest = false;
  39662. /**
  39663. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39664. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  39665. */
  39666. _this._useAlphaFresnel = false;
  39667. /**
  39668. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39669. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  39670. */
  39671. _this._useLinearAlphaFresnel = false;
  39672. /**
  39673. * The transparency mode of the material.
  39674. */
  39675. _this._transparencyMode = null;
  39676. /**
  39677. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  39678. * from cos thetav and roughness:
  39679. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  39680. */
  39681. _this._environmentBRDFTexture = null;
  39682. /**
  39683. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  39684. */
  39685. _this._forceIrradianceInFragment = false;
  39686. /**
  39687. * Force normal to face away from face.
  39688. */
  39689. _this._forceNormalForward = false;
  39690. /**
  39691. * Force metallic workflow.
  39692. */
  39693. _this._forceMetallicWorkflow = false;
  39694. /**
  39695. * Stores the available render targets.
  39696. */
  39697. _this._renderTargets = new BABYLON.SmartArray(16);
  39698. /**
  39699. * Sets the global ambient color for the material used in lighting calculations.
  39700. */
  39701. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39702. // Setup the default processing configuration to the scene.
  39703. _this._attachImageProcessingConfiguration(null);
  39704. _this.getRenderTargetTextures = function () {
  39705. _this._renderTargets.reset();
  39706. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39707. _this._renderTargets.push(_this._reflectionTexture);
  39708. }
  39709. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39710. _this._renderTargets.push(_this._refractionTexture);
  39711. }
  39712. return _this._renderTargets;
  39713. };
  39714. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  39715. return _this;
  39716. }
  39717. /**
  39718. * Attaches a new image processing configuration to the PBR Material.
  39719. * @param configuration
  39720. */
  39721. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39722. var _this = this;
  39723. if (configuration === this._imageProcessingConfiguration) {
  39724. return;
  39725. }
  39726. // Detaches observer.
  39727. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39728. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39729. }
  39730. // Pick the scene configuration if needed.
  39731. if (!configuration) {
  39732. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39733. }
  39734. else {
  39735. this._imageProcessingConfiguration = configuration;
  39736. }
  39737. // Attaches observer.
  39738. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39739. _this._markAllSubMeshesAsImageProcessingDirty();
  39740. });
  39741. };
  39742. /**
  39743. * Gets the name of the material class.
  39744. */
  39745. PBRBaseMaterial.prototype.getClassName = function () {
  39746. return "PBRBaseMaterial";
  39747. };
  39748. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  39749. /**
  39750. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  39751. */
  39752. get: function () {
  39753. return this._useLogarithmicDepth;
  39754. },
  39755. /**
  39756. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  39757. */
  39758. set: function (value) {
  39759. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39760. },
  39761. enumerable: true,
  39762. configurable: true
  39763. });
  39764. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  39765. /**
  39766. * Gets the current transparency mode.
  39767. */
  39768. get: function () {
  39769. return this._transparencyMode;
  39770. },
  39771. /**
  39772. * Sets the transparency mode of the material.
  39773. */
  39774. set: function (value) {
  39775. if (this._transparencyMode === value) {
  39776. return;
  39777. }
  39778. this._transparencyMode = value;
  39779. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  39780. this._markAllSubMeshesAsTexturesAndMiscDirty();
  39781. },
  39782. enumerable: true,
  39783. configurable: true
  39784. });
  39785. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  39786. /**
  39787. * Returns true if alpha blending should be disabled.
  39788. */
  39789. get: function () {
  39790. return (this._linkRefractionWithTransparency ||
  39791. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  39792. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  39793. },
  39794. enumerable: true,
  39795. configurable: true
  39796. });
  39797. /**
  39798. * Specifies whether or not this material should be rendered in alpha blend mode.
  39799. */
  39800. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  39801. if (this._disableAlphaBlending) {
  39802. return false;
  39803. }
  39804. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  39805. };
  39806. /**
  39807. * Specifies if the mesh will require alpha blending.
  39808. * @param mesh - BJS mesh.
  39809. */
  39810. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  39811. if (this._disableAlphaBlending) {
  39812. return false;
  39813. }
  39814. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  39815. };
  39816. /**
  39817. * Specifies whether or not this material should be rendered in alpha test mode.
  39818. */
  39819. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  39820. if (this._forceAlphaTest) {
  39821. return true;
  39822. }
  39823. if (this._linkRefractionWithTransparency) {
  39824. return false;
  39825. }
  39826. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  39827. };
  39828. /**
  39829. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  39830. */
  39831. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  39832. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  39833. };
  39834. /**
  39835. * Gets the texture used for the alpha test.
  39836. */
  39837. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  39838. return this._albedoTexture;
  39839. };
  39840. /**
  39841. * Specifies that the submesh is ready to be used.
  39842. * @param mesh - BJS mesh.
  39843. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  39844. * @param useInstances - Specifies that instances should be used.
  39845. * @returns - boolean indicating that the submesh is ready or not.
  39846. */
  39847. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39848. var _this = this;
  39849. if (subMesh.effect && this.isFrozen) {
  39850. if (this._wasPreviouslyReady) {
  39851. return true;
  39852. }
  39853. }
  39854. if (!subMesh._materialDefines) {
  39855. subMesh._materialDefines = new PBRMaterialDefines();
  39856. }
  39857. var scene = this.getScene();
  39858. var defines = subMesh._materialDefines;
  39859. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39860. if (defines._renderId === scene.getRenderId()) {
  39861. return true;
  39862. }
  39863. }
  39864. var engine = scene.getEngine();
  39865. // Lights
  39866. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39867. defines._needNormals = true;
  39868. // Textures
  39869. if (defines._areTexturesDirty) {
  39870. defines._needUVs = false;
  39871. if (scene.texturesEnabled) {
  39872. if (scene.getEngine().getCaps().textureLOD) {
  39873. defines.LODBASEDMICROSFURACE = true;
  39874. }
  39875. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  39876. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  39877. return false;
  39878. }
  39879. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  39880. }
  39881. else {
  39882. defines.ALBEDO = false;
  39883. }
  39884. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  39885. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39886. return false;
  39887. }
  39888. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39889. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  39890. }
  39891. else {
  39892. defines.AMBIENT = false;
  39893. }
  39894. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  39895. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39896. return false;
  39897. }
  39898. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39899. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39900. }
  39901. else {
  39902. defines.OPACITY = false;
  39903. }
  39904. var reflectionTexture = this._getReflectionTexture();
  39905. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  39906. if (!reflectionTexture.isReadyOrNotBlocking()) {
  39907. return false;
  39908. }
  39909. defines.REFLECTION = true;
  39910. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  39911. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  39912. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  39913. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  39914. defines.INVERTCUBICMAP = true;
  39915. }
  39916. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  39917. switch (reflectionTexture.coordinatesMode) {
  39918. case BABYLON.Texture.CUBIC_MODE:
  39919. case BABYLON.Texture.INVCUBIC_MODE:
  39920. defines.REFLECTIONMAP_CUBIC = true;
  39921. break;
  39922. case BABYLON.Texture.EXPLICIT_MODE:
  39923. defines.REFLECTIONMAP_EXPLICIT = true;
  39924. break;
  39925. case BABYLON.Texture.PLANAR_MODE:
  39926. defines.REFLECTIONMAP_PLANAR = true;
  39927. break;
  39928. case BABYLON.Texture.PROJECTION_MODE:
  39929. defines.REFLECTIONMAP_PROJECTION = true;
  39930. break;
  39931. case BABYLON.Texture.SKYBOX_MODE:
  39932. defines.REFLECTIONMAP_SKYBOX = true;
  39933. break;
  39934. case BABYLON.Texture.SPHERICAL_MODE:
  39935. defines.REFLECTIONMAP_SPHERICAL = true;
  39936. break;
  39937. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39938. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  39939. break;
  39940. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39941. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  39942. break;
  39943. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39944. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  39945. break;
  39946. }
  39947. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  39948. if (reflectionTexture.sphericalPolynomial) {
  39949. defines.USESPHERICALFROMREFLECTIONMAP = true;
  39950. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  39951. defines.USESPHERICALINVERTEX = false;
  39952. }
  39953. else {
  39954. defines.USESPHERICALINVERTEX = true;
  39955. }
  39956. }
  39957. }
  39958. }
  39959. else {
  39960. defines.REFLECTION = false;
  39961. defines.REFLECTIONMAP_3D = false;
  39962. defines.REFLECTIONMAP_SPHERICAL = false;
  39963. defines.REFLECTIONMAP_PLANAR = false;
  39964. defines.REFLECTIONMAP_CUBIC = false;
  39965. defines.REFLECTIONMAP_PROJECTION = false;
  39966. defines.REFLECTIONMAP_SKYBOX = false;
  39967. defines.REFLECTIONMAP_EXPLICIT = false;
  39968. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39969. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39970. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39971. defines.INVERTCUBICMAP = false;
  39972. defines.USESPHERICALFROMREFLECTIONMAP = false;
  39973. defines.USESPHERICALINVERTEX = false;
  39974. defines.REFLECTIONMAP_OPPOSITEZ = false;
  39975. defines.LODINREFLECTIONALPHA = false;
  39976. defines.GAMMAREFLECTION = false;
  39977. }
  39978. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  39979. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39980. return false;
  39981. }
  39982. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39983. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39984. }
  39985. else {
  39986. defines.LIGHTMAP = false;
  39987. }
  39988. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  39989. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39990. return false;
  39991. }
  39992. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39993. }
  39994. else {
  39995. defines.EMISSIVE = false;
  39996. }
  39997. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  39998. if (this._metallicTexture) {
  39999. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40000. return false;
  40001. }
  40002. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  40003. defines.METALLICWORKFLOW = true;
  40004. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  40005. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  40006. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  40007. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  40008. }
  40009. else if (this._reflectivityTexture) {
  40010. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40011. return false;
  40012. }
  40013. defines.METALLICWORKFLOW = false;
  40014. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  40015. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  40016. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  40017. }
  40018. else {
  40019. defines.METALLICWORKFLOW = false;
  40020. defines.REFLECTIVITY = false;
  40021. }
  40022. if (this._microSurfaceTexture) {
  40023. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40024. return false;
  40025. }
  40026. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  40027. }
  40028. else {
  40029. defines.MICROSURFACEMAP = false;
  40030. }
  40031. }
  40032. else {
  40033. defines.REFLECTIVITY = false;
  40034. defines.MICROSURFACEMAP = false;
  40035. }
  40036. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40037. // Bump texure can not be none blocking.
  40038. if (!this._bumpTexture.isReady()) {
  40039. return false;
  40040. }
  40041. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  40042. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40043. defines.PARALLAX = true;
  40044. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  40045. }
  40046. else {
  40047. defines.PARALLAX = false;
  40048. }
  40049. }
  40050. else {
  40051. defines.BUMP = false;
  40052. }
  40053. var refractionTexture = this._getRefractionTexture();
  40054. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40055. if (!refractionTexture.isReadyOrNotBlocking()) {
  40056. return false;
  40057. }
  40058. defines.REFRACTION = true;
  40059. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  40060. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  40061. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  40062. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  40063. if (this._linkRefractionWithTransparency) {
  40064. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  40065. }
  40066. }
  40067. else {
  40068. defines.REFRACTION = false;
  40069. }
  40070. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40071. // This is blocking.
  40072. if (!this._environmentBRDFTexture.isReady()) {
  40073. return false;
  40074. }
  40075. defines.ENVIRONMENTBRDF = true;
  40076. }
  40077. else {
  40078. defines.ENVIRONMENTBRDF = false;
  40079. }
  40080. if (this._shouldUseAlphaFromAlbedoTexture()) {
  40081. defines.ALPHAFROMALBEDO = true;
  40082. }
  40083. else {
  40084. defines.ALPHAFROMALBEDO = false;
  40085. }
  40086. }
  40087. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  40088. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  40089. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  40090. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  40091. defines.METALLICWORKFLOW = true;
  40092. }
  40093. else {
  40094. defines.METALLICWORKFLOW = false;
  40095. }
  40096. if (!this.backFaceCulling && this._twoSidedLighting) {
  40097. defines.TWOSIDEDLIGHTING = true;
  40098. }
  40099. else {
  40100. defines.TWOSIDEDLIGHTING = false;
  40101. }
  40102. defines.ALPHATESTVALUE = this._alphaCutOff;
  40103. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  40104. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  40105. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  40106. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  40107. }
  40108. if (defines._areImageProcessingDirty) {
  40109. if (!this._imageProcessingConfiguration.isReady()) {
  40110. return false;
  40111. }
  40112. this._imageProcessingConfiguration.prepareDefines(defines);
  40113. }
  40114. defines.FORCENORMALFORWARD = this._forceNormalForward;
  40115. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  40116. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  40117. // Misc.
  40118. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  40119. // Values that need to be evaluated on every frame
  40120. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false);
  40121. // Attribs
  40122. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  40123. var bufferMesh = null;
  40124. if (mesh instanceof BABYLON.InstancedMesh) {
  40125. bufferMesh = mesh.sourceMesh;
  40126. }
  40127. else if (mesh instanceof BABYLON.Mesh) {
  40128. bufferMesh = mesh;
  40129. }
  40130. if (bufferMesh) {
  40131. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40132. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  40133. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  40134. var normals = normalVertexBuffer.getData();
  40135. var vertexBufferOffset = normalVertexBuffer.getOffset();
  40136. var strideSize = normalVertexBuffer.getStrideSize();
  40137. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  40138. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  40139. defines.NORMAL = false;
  40140. }
  40141. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40142. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  40143. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  40144. var tangents = tangentVertexBuffer.getData();
  40145. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  40146. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  40147. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  40148. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  40149. defines.TANGENT = false;
  40150. }
  40151. }
  40152. }
  40153. else {
  40154. if (!scene.getEngine().getCaps().standardDerivatives) {
  40155. bufferMesh.createNormals(true);
  40156. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  40157. }
  40158. }
  40159. }
  40160. }
  40161. // Get correct effect
  40162. if (defines.isDirty) {
  40163. defines.markAsProcessed();
  40164. scene.resetCachedMaterial();
  40165. // Fallbacks
  40166. var fallbacks = new BABYLON.EffectFallbacks();
  40167. var fallbackRank = 0;
  40168. if (defines.USESPHERICALINVERTEX) {
  40169. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  40170. }
  40171. if (defines.FOG) {
  40172. fallbacks.addFallback(fallbackRank, "FOG");
  40173. }
  40174. if (defines.POINTSIZE) {
  40175. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  40176. }
  40177. if (defines.LOGARITHMICDEPTH) {
  40178. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  40179. }
  40180. if (defines.PARALLAX) {
  40181. fallbacks.addFallback(fallbackRank, "PARALLAX");
  40182. }
  40183. if (defines.PARALLAXOCCLUSION) {
  40184. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  40185. }
  40186. if (defines.ENVIRONMENTBRDF) {
  40187. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  40188. }
  40189. if (defines.TANGENT) {
  40190. fallbacks.addFallback(fallbackRank++, "TANGENT");
  40191. }
  40192. if (defines.BUMP) {
  40193. fallbacks.addFallback(fallbackRank++, "BUMP");
  40194. }
  40195. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  40196. if (defines.SPECULARTERM) {
  40197. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  40198. }
  40199. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  40200. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  40201. }
  40202. if (defines.LIGHTMAP) {
  40203. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  40204. }
  40205. if (defines.NORMAL) {
  40206. fallbacks.addFallback(fallbackRank++, "NORMAL");
  40207. }
  40208. if (defines.AMBIENT) {
  40209. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  40210. }
  40211. if (defines.EMISSIVE) {
  40212. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  40213. }
  40214. if (defines.VERTEXCOLOR) {
  40215. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  40216. }
  40217. if (defines.NUM_BONE_INFLUENCERS > 0) {
  40218. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  40219. }
  40220. if (defines.MORPHTARGETS) {
  40221. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  40222. }
  40223. //Attributes
  40224. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40225. if (defines.NORMAL) {
  40226. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40227. }
  40228. if (defines.TANGENT) {
  40229. attribs.push(BABYLON.VertexBuffer.TangentKind);
  40230. }
  40231. if (defines.UV1) {
  40232. attribs.push(BABYLON.VertexBuffer.UVKind);
  40233. }
  40234. if (defines.UV2) {
  40235. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40236. }
  40237. if (defines.VERTEXCOLOR) {
  40238. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40239. }
  40240. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40241. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40242. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40243. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  40244. "vFogInfos", "vFogColor", "pointSize",
  40245. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40246. "mBones",
  40247. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  40248. "vLightingIntensity",
  40249. "logarithmicDepthConstant",
  40250. "vSphericalX", "vSphericalY", "vSphericalZ",
  40251. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  40252. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  40253. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  40254. "vTangentSpaceParams"
  40255. ];
  40256. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  40257. "bumpSampler", "lightmapSampler", "opacitySampler",
  40258. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  40259. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  40260. "microSurfaceSampler", "environmentBrdfSampler"];
  40261. var uniformBuffers = ["Material", "Scene"];
  40262. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40263. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40264. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40265. uniformsNames: uniforms,
  40266. uniformBuffersNames: uniformBuffers,
  40267. samplers: samplers,
  40268. defines: defines,
  40269. maxSimultaneousLights: this._maxSimultaneousLights
  40270. });
  40271. var onCompiled = function (effect) {
  40272. if (_this.onCompiled) {
  40273. _this.onCompiled(effect);
  40274. }
  40275. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  40276. };
  40277. var join = defines.toString();
  40278. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  40279. attributes: attribs,
  40280. uniformsNames: uniforms,
  40281. uniformBuffersNames: uniformBuffers,
  40282. samplers: samplers,
  40283. defines: join,
  40284. fallbacks: fallbacks,
  40285. onCompiled: onCompiled,
  40286. onError: this.onError,
  40287. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40288. }, engine), defines);
  40289. this.buildUniformLayout();
  40290. }
  40291. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40292. return false;
  40293. }
  40294. defines._renderId = scene.getRenderId();
  40295. this._wasPreviouslyReady = true;
  40296. return true;
  40297. };
  40298. /**
  40299. * Initializes the uniform buffer layout for the shader.
  40300. */
  40301. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  40302. // Order is important !
  40303. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  40304. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  40305. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40306. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40307. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40308. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  40309. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  40310. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40311. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40312. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40313. this._uniformBuffer.addUniform("albedoMatrix", 16);
  40314. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40315. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40316. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40317. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40318. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  40319. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  40320. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40321. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40322. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40323. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40324. this._uniformBuffer.addUniform("vReflectionColor", 3);
  40325. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  40326. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  40327. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  40328. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  40329. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  40330. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40331. this._uniformBuffer.addUniform("pointSize", 1);
  40332. this._uniformBuffer.create();
  40333. };
  40334. /**
  40335. * Unbinds the textures.
  40336. */
  40337. PBRBaseMaterial.prototype.unbind = function () {
  40338. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40339. this._uniformBuffer.setTexture("reflectionSampler", null);
  40340. }
  40341. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40342. this._uniformBuffer.setTexture("refractionSampler", null);
  40343. }
  40344. _super.prototype.unbind.call(this);
  40345. };
  40346. /**
  40347. * Binds to the world matrix.
  40348. * @param world - The world matrix.
  40349. */
  40350. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  40351. this._activeEffect.setMatrix("world", world);
  40352. };
  40353. /**
  40354. * Binds the submesh data.
  40355. * @param world - The world matrix.
  40356. * @param mesh - The BJS mesh.
  40357. * @param subMesh - A submesh of the BJS mesh.
  40358. */
  40359. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40360. var scene = this.getScene();
  40361. var defines = subMesh._materialDefines;
  40362. if (!defines) {
  40363. return;
  40364. }
  40365. var effect = subMesh.effect;
  40366. if (!effect) {
  40367. return;
  40368. }
  40369. this._activeEffect = effect;
  40370. // Matrices
  40371. this.bindOnlyWorldMatrix(world);
  40372. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40373. // Bones
  40374. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  40375. var reflectionTexture = null;
  40376. if (mustRebind) {
  40377. this._uniformBuffer.bindToEffect(effect, "Material");
  40378. this.bindViewProjection(effect);
  40379. reflectionTexture = this._getReflectionTexture();
  40380. var refractionTexture = this._getRefractionTexture();
  40381. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40382. // Texture uniforms
  40383. if (scene.texturesEnabled) {
  40384. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40385. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  40386. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  40387. }
  40388. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40389. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  40390. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40391. }
  40392. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40393. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40394. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40395. }
  40396. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40397. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  40398. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  40399. var polynomials = reflectionTexture.sphericalPolynomial;
  40400. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  40401. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  40402. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  40403. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  40404. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  40405. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  40406. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  40407. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  40408. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  40409. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  40410. }
  40411. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  40412. }
  40413. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40414. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40415. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40416. }
  40417. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40418. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40419. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40420. }
  40421. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40422. if (this._metallicTexture) {
  40423. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  40424. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  40425. }
  40426. else if (this._reflectivityTexture) {
  40427. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  40428. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  40429. }
  40430. if (this._microSurfaceTexture) {
  40431. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  40432. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  40433. }
  40434. }
  40435. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40436. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  40437. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40438. if (scene._mirroredCameraPosition) {
  40439. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40440. }
  40441. else {
  40442. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40443. }
  40444. }
  40445. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40446. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  40447. var depth = 1.0;
  40448. if (!refractionTexture.isCube) {
  40449. if (refractionTexture.depth) {
  40450. depth = refractionTexture.depth;
  40451. }
  40452. }
  40453. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  40454. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  40455. }
  40456. }
  40457. // Point size
  40458. if (this.pointsCloud) {
  40459. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40460. }
  40461. // Colors
  40462. if (defines.METALLICWORKFLOW) {
  40463. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  40464. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  40465. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  40466. }
  40467. else {
  40468. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  40469. }
  40470. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  40471. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  40472. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  40473. // Misc
  40474. this._lightingInfos.x = this._directIntensity;
  40475. this._lightingInfos.y = this._emissiveIntensity;
  40476. this._lightingInfos.z = this._environmentIntensity;
  40477. this._lightingInfos.w = this._specularIntensity;
  40478. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  40479. }
  40480. // Textures
  40481. if (scene.texturesEnabled) {
  40482. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40483. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  40484. }
  40485. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40486. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  40487. }
  40488. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40489. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  40490. }
  40491. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40492. if (defines.LODBASEDMICROSFURACE) {
  40493. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  40494. }
  40495. else {
  40496. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  40497. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  40498. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  40499. }
  40500. }
  40501. if (defines.ENVIRONMENTBRDF) {
  40502. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  40503. }
  40504. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40505. if (defines.LODBASEDMICROSFURACE) {
  40506. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  40507. }
  40508. else {
  40509. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  40510. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  40511. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  40512. }
  40513. }
  40514. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40515. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  40516. }
  40517. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40518. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  40519. }
  40520. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40521. if (this._metallicTexture) {
  40522. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  40523. }
  40524. else if (this._reflectivityTexture) {
  40525. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  40526. }
  40527. if (this._microSurfaceTexture) {
  40528. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  40529. }
  40530. }
  40531. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40532. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  40533. }
  40534. }
  40535. // Clip plane
  40536. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  40537. // Colors
  40538. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  40539. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40540. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  40541. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  40542. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  40543. }
  40544. if (mustRebind || !this.isFrozen) {
  40545. // Lights
  40546. if (scene.lightsEnabled && !this._disableLighting) {
  40547. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  40548. }
  40549. // View
  40550. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  40551. this.bindView(effect);
  40552. }
  40553. // Fog
  40554. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  40555. // Morph targets
  40556. if (defines.NUM_MORPH_INFLUENCERS) {
  40557. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  40558. }
  40559. // image processing
  40560. this._imageProcessingConfiguration.bind(this._activeEffect);
  40561. // Log. depth
  40562. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  40563. }
  40564. this._uniformBuffer.update();
  40565. this._afterBind(mesh);
  40566. };
  40567. /**
  40568. * Returns the animatable textures.
  40569. * @returns - Array of animatable textures.
  40570. */
  40571. PBRBaseMaterial.prototype.getAnimatables = function () {
  40572. var results = [];
  40573. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  40574. results.push(this._albedoTexture);
  40575. }
  40576. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  40577. results.push(this._ambientTexture);
  40578. }
  40579. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  40580. results.push(this._opacityTexture);
  40581. }
  40582. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40583. results.push(this._reflectionTexture);
  40584. }
  40585. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40586. results.push(this._emissiveTexture);
  40587. }
  40588. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  40589. results.push(this._metallicTexture);
  40590. }
  40591. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  40592. results.push(this._reflectivityTexture);
  40593. }
  40594. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40595. results.push(this._bumpTexture);
  40596. }
  40597. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40598. results.push(this._lightmapTexture);
  40599. }
  40600. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40601. results.push(this._refractionTexture);
  40602. }
  40603. return results;
  40604. };
  40605. /**
  40606. * Returns the texture used for reflections.
  40607. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  40608. */
  40609. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  40610. if (this._reflectionTexture) {
  40611. return this._reflectionTexture;
  40612. }
  40613. return this.getScene().environmentTexture;
  40614. };
  40615. /**
  40616. * Returns the texture used for refraction or null if none is used.
  40617. * @returns - Refection texture if present. If no refraction texture and refraction
  40618. * is linked with transparency, returns environment texture. Otherwise, returns null.
  40619. */
  40620. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  40621. if (this._refractionTexture) {
  40622. return this._refractionTexture;
  40623. }
  40624. if (this._linkRefractionWithTransparency) {
  40625. return this.getScene().environmentTexture;
  40626. }
  40627. return null;
  40628. };
  40629. /**
  40630. * Disposes the resources of the material.
  40631. * @param forceDisposeEffect - Forces the disposal of effects.
  40632. * @param forceDisposeTextures - Forces the disposal of all textures.
  40633. */
  40634. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40635. if (forceDisposeTextures) {
  40636. if (this._albedoTexture) {
  40637. this._albedoTexture.dispose();
  40638. }
  40639. if (this._ambientTexture) {
  40640. this._ambientTexture.dispose();
  40641. }
  40642. if (this._opacityTexture) {
  40643. this._opacityTexture.dispose();
  40644. }
  40645. if (this._reflectionTexture) {
  40646. this._reflectionTexture.dispose();
  40647. }
  40648. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  40649. this._environmentBRDFTexture.dispose();
  40650. }
  40651. if (this._emissiveTexture) {
  40652. this._emissiveTexture.dispose();
  40653. }
  40654. if (this._metallicTexture) {
  40655. this._metallicTexture.dispose();
  40656. }
  40657. if (this._reflectivityTexture) {
  40658. this._reflectivityTexture.dispose();
  40659. }
  40660. if (this._bumpTexture) {
  40661. this._bumpTexture.dispose();
  40662. }
  40663. if (this._lightmapTexture) {
  40664. this._lightmapTexture.dispose();
  40665. }
  40666. if (this._refractionTexture) {
  40667. this._refractionTexture.dispose();
  40668. }
  40669. }
  40670. this._renderTargets.dispose();
  40671. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40672. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40673. }
  40674. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40675. };
  40676. /**
  40677. * Stores the reflectivity values based on metallic roughness workflow.
  40678. */
  40679. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  40680. __decorate([
  40681. BABYLON.serializeAsImageProcessingConfiguration()
  40682. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  40683. __decorate([
  40684. BABYLON.serialize()
  40685. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  40686. __decorate([
  40687. BABYLON.serialize()
  40688. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  40689. return PBRBaseMaterial;
  40690. }(BABYLON.PushMaterial));
  40691. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  40692. })(BABYLON || (BABYLON = {}));
  40693. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  40694. var BABYLON;
  40695. (function (BABYLON) {
  40696. /**
  40697. * The Physically based simple base material of BJS.
  40698. *
  40699. * This enables better naming and convention enforcements on top of the pbrMaterial.
  40700. * It is used as the base class for both the specGloss and metalRough conventions.
  40701. */
  40702. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  40703. __extends(PBRBaseSimpleMaterial, _super);
  40704. /**
  40705. * Instantiates a new PBRMaterial instance.
  40706. *
  40707. * @param name The material name
  40708. * @param scene The scene the material will be use in.
  40709. */
  40710. function PBRBaseSimpleMaterial(name, scene) {
  40711. var _this = _super.call(this, name, scene) || this;
  40712. /**
  40713. * Number of Simultaneous lights allowed on the material.
  40714. */
  40715. _this.maxSimultaneousLights = 4;
  40716. /**
  40717. * If sets to true, disables all the lights affecting the material.
  40718. */
  40719. _this.disableLighting = false;
  40720. /**
  40721. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  40722. */
  40723. _this.invertNormalMapX = false;
  40724. /**
  40725. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  40726. */
  40727. _this.invertNormalMapY = false;
  40728. /**
  40729. * Emissivie color used to self-illuminate the model.
  40730. */
  40731. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  40732. /**
  40733. * Occlusion Channel Strenght.
  40734. */
  40735. _this.occlusionStrength = 1.0;
  40736. _this.useLightmapAsShadowmap = false;
  40737. _this._useAlphaFromAlbedoTexture = true;
  40738. _this._useAmbientInGrayScale = true;
  40739. return _this;
  40740. }
  40741. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  40742. /**
  40743. * Gets the current double sided mode.
  40744. */
  40745. get: function () {
  40746. return this._twoSidedLighting;
  40747. },
  40748. /**
  40749. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40750. */
  40751. set: function (value) {
  40752. if (this._twoSidedLighting === value) {
  40753. return;
  40754. }
  40755. this._twoSidedLighting = value;
  40756. this.backFaceCulling = !value;
  40757. this._markAllSubMeshesAsTexturesDirty();
  40758. },
  40759. enumerable: true,
  40760. configurable: true
  40761. });
  40762. /**
  40763. * Return the active textures of the material.
  40764. */
  40765. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  40766. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40767. if (this.environmentTexture) {
  40768. activeTextures.push(this.environmentTexture);
  40769. }
  40770. if (this.normalTexture) {
  40771. activeTextures.push(this.normalTexture);
  40772. }
  40773. if (this.emissiveTexture) {
  40774. activeTextures.push(this.emissiveTexture);
  40775. }
  40776. if (this.occlusionTexture) {
  40777. activeTextures.push(this.occlusionTexture);
  40778. }
  40779. if (this.lightmapTexture) {
  40780. activeTextures.push(this.lightmapTexture);
  40781. }
  40782. return activeTextures;
  40783. };
  40784. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  40785. if (_super.prototype.hasTexture.call(this, texture)) {
  40786. return true;
  40787. }
  40788. if (this.lightmapTexture === texture) {
  40789. return true;
  40790. }
  40791. return false;
  40792. };
  40793. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  40794. return "PBRBaseSimpleMaterial";
  40795. };
  40796. __decorate([
  40797. BABYLON.serialize(),
  40798. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40799. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  40800. __decorate([
  40801. BABYLON.serialize(),
  40802. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40803. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  40804. __decorate([
  40805. BABYLON.serializeAsTexture(),
  40806. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  40807. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  40808. __decorate([
  40809. BABYLON.serialize(),
  40810. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40811. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  40812. __decorate([
  40813. BABYLON.serialize(),
  40814. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40815. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  40816. __decorate([
  40817. BABYLON.serializeAsTexture(),
  40818. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  40819. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  40820. __decorate([
  40821. BABYLON.serializeAsColor3("emissive"),
  40822. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40823. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  40824. __decorate([
  40825. BABYLON.serializeAsTexture(),
  40826. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40827. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  40828. __decorate([
  40829. BABYLON.serialize(),
  40830. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  40831. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  40832. __decorate([
  40833. BABYLON.serializeAsTexture(),
  40834. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  40835. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  40836. __decorate([
  40837. BABYLON.serialize(),
  40838. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  40839. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  40840. __decorate([
  40841. BABYLON.serialize()
  40842. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  40843. __decorate([
  40844. BABYLON.serializeAsTexture(),
  40845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  40846. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  40847. __decorate([
  40848. BABYLON.serialize(),
  40849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40850. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40851. return PBRBaseSimpleMaterial;
  40852. }(BABYLON.PBRBaseMaterial));
  40853. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  40854. })(BABYLON || (BABYLON = {}));
  40855. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  40856. var BABYLON;
  40857. (function (BABYLON) {
  40858. /**
  40859. * The Physically based material of BJS.
  40860. *
  40861. * This offers the main features of a standard PBR material.
  40862. * For more information, please refer to the documentation :
  40863. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40864. */
  40865. var PBRMaterial = /** @class */ (function (_super) {
  40866. __extends(PBRMaterial, _super);
  40867. /**
  40868. * Instantiates a new PBRMaterial instance.
  40869. *
  40870. * @param name The material name
  40871. * @param scene The scene the material will be use in.
  40872. */
  40873. function PBRMaterial(name, scene) {
  40874. var _this = _super.call(this, name, scene) || this;
  40875. /**
  40876. * Intensity of the direct lights e.g. the four lights available in your scene.
  40877. * This impacts both the direct diffuse and specular highlights.
  40878. */
  40879. _this.directIntensity = 1.0;
  40880. /**
  40881. * Intensity of the emissive part of the material.
  40882. * This helps controlling the emissive effect without modifying the emissive color.
  40883. */
  40884. _this.emissiveIntensity = 1.0;
  40885. /**
  40886. * Intensity of the environment e.g. how much the environment will light the object
  40887. * either through harmonics for rough material or through the refelction for shiny ones.
  40888. */
  40889. _this.environmentIntensity = 1.0;
  40890. /**
  40891. * This is a special control allowing the reduction of the specular highlights coming from the
  40892. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  40893. */
  40894. _this.specularIntensity = 1.0;
  40895. /**
  40896. * Debug Control allowing disabling the bump map on this material.
  40897. */
  40898. _this.disableBumpMap = false;
  40899. /**
  40900. * AKA Occlusion Texture Intensity in other nomenclature.
  40901. */
  40902. _this.ambientTextureStrength = 1.0;
  40903. /**
  40904. * The color of a material in ambient lighting.
  40905. */
  40906. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  40907. /**
  40908. * AKA Diffuse Color in other nomenclature.
  40909. */
  40910. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  40911. /**
  40912. * AKA Specular Color in other nomenclature.
  40913. */
  40914. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40915. /**
  40916. * The color reflected from the material.
  40917. */
  40918. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  40919. /**
  40920. * The color emitted from the material.
  40921. */
  40922. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  40923. /**
  40924. * AKA Glossiness in other nomenclature.
  40925. */
  40926. _this.microSurface = 1.0;
  40927. /**
  40928. * source material index of refraction (IOR)' / 'destination material IOR.
  40929. */
  40930. _this.indexOfRefraction = 0.66;
  40931. /**
  40932. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40933. */
  40934. _this.invertRefractionY = false;
  40935. /**
  40936. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40937. * Materials half opaque for instance using refraction could benefit from this control.
  40938. */
  40939. _this.linkRefractionWithTransparency = false;
  40940. _this.useLightmapAsShadowmap = false;
  40941. /**
  40942. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40943. */
  40944. _this.useAlphaFromAlbedoTexture = false;
  40945. /**
  40946. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40947. */
  40948. _this.forceAlphaTest = false;
  40949. /**
  40950. * Defines the alpha limits in alpha test mode.
  40951. */
  40952. _this.alphaCutOff = 0.4;
  40953. /**
  40954. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40955. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40956. */
  40957. _this.useSpecularOverAlpha = true;
  40958. /**
  40959. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40960. */
  40961. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  40962. /**
  40963. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40964. */
  40965. _this.useRoughnessFromMetallicTextureAlpha = true;
  40966. /**
  40967. * Specifies if the metallic texture contains the roughness information in its green channel.
  40968. */
  40969. _this.useRoughnessFromMetallicTextureGreen = false;
  40970. /**
  40971. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40972. */
  40973. _this.useMetallnessFromMetallicTextureBlue = false;
  40974. /**
  40975. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40976. */
  40977. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  40978. /**
  40979. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40980. */
  40981. _this.useAmbientInGrayScale = false;
  40982. /**
  40983. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40984. * The material will try to infer what glossiness each pixel should be.
  40985. */
  40986. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  40987. /**
  40988. * BJS is using an harcoded light falloff based on a manually sets up range.
  40989. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40990. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40991. */
  40992. _this.usePhysicalLightFalloff = true;
  40993. /**
  40994. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40995. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40996. */
  40997. _this.useRadianceOverAlpha = true;
  40998. /**
  40999. * Allows using the bump map in parallax mode.
  41000. */
  41001. _this.useParallax = false;
  41002. /**
  41003. * Allows using the bump map in parallax occlusion mode.
  41004. */
  41005. _this.useParallaxOcclusion = false;
  41006. /**
  41007. * Controls the scale bias of the parallax mode.
  41008. */
  41009. _this.parallaxScaleBias = 0.05;
  41010. /**
  41011. * If sets to true, disables all the lights affecting the material.
  41012. */
  41013. _this.disableLighting = false;
  41014. /**
  41015. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41016. */
  41017. _this.forceIrradianceInFragment = false;
  41018. /**
  41019. * Number of Simultaneous lights allowed on the material.
  41020. */
  41021. _this.maxSimultaneousLights = 4;
  41022. /**
  41023. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41024. */
  41025. _this.invertNormalMapX = false;
  41026. /**
  41027. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41028. */
  41029. _this.invertNormalMapY = false;
  41030. /**
  41031. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41032. */
  41033. _this.twoSidedLighting = false;
  41034. /**
  41035. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41036. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41037. */
  41038. _this.useAlphaFresnel = false;
  41039. /**
  41040. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41041. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41042. */
  41043. _this.useLinearAlphaFresnel = false;
  41044. /**
  41045. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41046. * And/Or occlude the blended part.
  41047. */
  41048. _this.environmentBRDFTexture = null;
  41049. /**
  41050. * Force normal to face away from face.
  41051. */
  41052. _this.forceNormalForward = false;
  41053. /**
  41054. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41055. * makes the reflect vector face the model (under horizon).
  41056. */
  41057. _this.useHorizonOcclusion = true;
  41058. /**
  41059. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41060. * too much the area relying on ambient texture to define their ambient occlusion.
  41061. */
  41062. _this.useRadianceOcclusion = true;
  41063. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41064. return _this;
  41065. }
  41066. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  41067. /**
  41068. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  41069. */
  41070. get: function () {
  41071. return this._PBRMATERIAL_OPAQUE;
  41072. },
  41073. enumerable: true,
  41074. configurable: true
  41075. });
  41076. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  41077. /**
  41078. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41079. */
  41080. get: function () {
  41081. return this._PBRMATERIAL_ALPHATEST;
  41082. },
  41083. enumerable: true,
  41084. configurable: true
  41085. });
  41086. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  41087. /**
  41088. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41089. */
  41090. get: function () {
  41091. return this._PBRMATERIAL_ALPHABLEND;
  41092. },
  41093. enumerable: true,
  41094. configurable: true
  41095. });
  41096. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  41097. /**
  41098. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41099. * They are also discarded below the alpha cutoff threshold to improve performances.
  41100. */
  41101. get: function () {
  41102. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  41103. },
  41104. enumerable: true,
  41105. configurable: true
  41106. });
  41107. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  41108. /**
  41109. * Gets the image processing configuration used either in this material.
  41110. */
  41111. get: function () {
  41112. return this._imageProcessingConfiguration;
  41113. },
  41114. /**
  41115. * Sets the Default image processing configuration used either in the this material.
  41116. *
  41117. * If sets to null, the scene one is in use.
  41118. */
  41119. set: function (value) {
  41120. this._attachImageProcessingConfiguration(value);
  41121. // Ensure the effect will be rebuilt.
  41122. this._markAllSubMeshesAsTexturesDirty();
  41123. },
  41124. enumerable: true,
  41125. configurable: true
  41126. });
  41127. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  41128. /**
  41129. * Gets wether the color curves effect is enabled.
  41130. */
  41131. get: function () {
  41132. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41133. },
  41134. /**
  41135. * Sets wether the color curves effect is enabled.
  41136. */
  41137. set: function (value) {
  41138. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41139. },
  41140. enumerable: true,
  41141. configurable: true
  41142. });
  41143. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  41144. /**
  41145. * Gets wether the color grading effect is enabled.
  41146. */
  41147. get: function () {
  41148. return this.imageProcessingConfiguration.colorGradingEnabled;
  41149. },
  41150. /**
  41151. * Gets wether the color grading effect is enabled.
  41152. */
  41153. set: function (value) {
  41154. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41155. },
  41156. enumerable: true,
  41157. configurable: true
  41158. });
  41159. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  41160. /**
  41161. * Gets wether tonemapping is enabled or not.
  41162. */
  41163. get: function () {
  41164. return this._imageProcessingConfiguration.toneMappingEnabled;
  41165. },
  41166. /**
  41167. * Sets wether tonemapping is enabled or not
  41168. */
  41169. set: function (value) {
  41170. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41171. },
  41172. enumerable: true,
  41173. configurable: true
  41174. });
  41175. ;
  41176. ;
  41177. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  41178. /**
  41179. * The camera exposure used on this material.
  41180. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41181. * This corresponds to a photographic exposure.
  41182. */
  41183. get: function () {
  41184. return this._imageProcessingConfiguration.exposure;
  41185. },
  41186. /**
  41187. * The camera exposure used on this material.
  41188. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41189. * This corresponds to a photographic exposure.
  41190. */
  41191. set: function (value) {
  41192. this._imageProcessingConfiguration.exposure = value;
  41193. },
  41194. enumerable: true,
  41195. configurable: true
  41196. });
  41197. ;
  41198. ;
  41199. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  41200. /**
  41201. * Gets The camera contrast used on this material.
  41202. */
  41203. get: function () {
  41204. return this._imageProcessingConfiguration.contrast;
  41205. },
  41206. /**
  41207. * Sets The camera contrast used on this material.
  41208. */
  41209. set: function (value) {
  41210. this._imageProcessingConfiguration.contrast = value;
  41211. },
  41212. enumerable: true,
  41213. configurable: true
  41214. });
  41215. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  41216. /**
  41217. * Gets the Color Grading 2D Lookup Texture.
  41218. */
  41219. get: function () {
  41220. return this._imageProcessingConfiguration.colorGradingTexture;
  41221. },
  41222. /**
  41223. * Sets the Color Grading 2D Lookup Texture.
  41224. */
  41225. set: function (value) {
  41226. this._imageProcessingConfiguration.colorGradingTexture = value;
  41227. },
  41228. enumerable: true,
  41229. configurable: true
  41230. });
  41231. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  41232. /**
  41233. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41234. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41235. * 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;
  41236. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41237. */
  41238. get: function () {
  41239. return this._imageProcessingConfiguration.colorCurves;
  41240. },
  41241. /**
  41242. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41243. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41244. * 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;
  41245. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41246. */
  41247. set: function (value) {
  41248. this._imageProcessingConfiguration.colorCurves = value;
  41249. },
  41250. enumerable: true,
  41251. configurable: true
  41252. });
  41253. /**
  41254. * Returns the name of this material class.
  41255. */
  41256. PBRMaterial.prototype.getClassName = function () {
  41257. return "PBRMaterial";
  41258. };
  41259. /**
  41260. * Returns an array of the actively used textures.
  41261. * @returns - Array of BaseTextures
  41262. */
  41263. PBRMaterial.prototype.getActiveTextures = function () {
  41264. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41265. if (this._albedoTexture) {
  41266. activeTextures.push(this._albedoTexture);
  41267. }
  41268. if (this._ambientTexture) {
  41269. activeTextures.push(this._ambientTexture);
  41270. }
  41271. if (this._opacityTexture) {
  41272. activeTextures.push(this._opacityTexture);
  41273. }
  41274. if (this._reflectionTexture) {
  41275. activeTextures.push(this._reflectionTexture);
  41276. }
  41277. if (this._emissiveTexture) {
  41278. activeTextures.push(this._emissiveTexture);
  41279. }
  41280. if (this._reflectivityTexture) {
  41281. activeTextures.push(this._reflectivityTexture);
  41282. }
  41283. if (this._metallicTexture) {
  41284. activeTextures.push(this._metallicTexture);
  41285. }
  41286. if (this._microSurfaceTexture) {
  41287. activeTextures.push(this._microSurfaceTexture);
  41288. }
  41289. if (this._bumpTexture) {
  41290. activeTextures.push(this._bumpTexture);
  41291. }
  41292. if (this._lightmapTexture) {
  41293. activeTextures.push(this._lightmapTexture);
  41294. }
  41295. if (this._refractionTexture) {
  41296. activeTextures.push(this._refractionTexture);
  41297. }
  41298. return activeTextures;
  41299. };
  41300. /**
  41301. * Checks to see if a texture is used in the material.
  41302. * @param texture - Base texture to use.
  41303. * @returns - Boolean specifying if a texture is used in the material.
  41304. */
  41305. PBRMaterial.prototype.hasTexture = function (texture) {
  41306. if (_super.prototype.hasTexture.call(this, texture)) {
  41307. return true;
  41308. }
  41309. if (this._albedoTexture === texture) {
  41310. return true;
  41311. }
  41312. if (this._ambientTexture === texture) {
  41313. return true;
  41314. }
  41315. if (this._opacityTexture === texture) {
  41316. return true;
  41317. }
  41318. if (this._reflectionTexture === texture) {
  41319. return true;
  41320. }
  41321. if (this._reflectivityTexture === texture) {
  41322. return true;
  41323. }
  41324. if (this._metallicTexture === texture) {
  41325. return true;
  41326. }
  41327. if (this._microSurfaceTexture === texture) {
  41328. return true;
  41329. }
  41330. if (this._bumpTexture === texture) {
  41331. return true;
  41332. }
  41333. if (this._lightmapTexture === texture) {
  41334. return true;
  41335. }
  41336. if (this._refractionTexture === texture) {
  41337. return true;
  41338. }
  41339. return false;
  41340. };
  41341. /**
  41342. * Makes a duplicate of the current material.
  41343. * @param name - name to use for the new material.
  41344. */
  41345. PBRMaterial.prototype.clone = function (name) {
  41346. var _this = this;
  41347. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  41348. clone.id = name;
  41349. clone.name = name;
  41350. return clone;
  41351. };
  41352. /**
  41353. * Serializes this PBR Material.
  41354. * @returns - An object with the serialized material.
  41355. */
  41356. PBRMaterial.prototype.serialize = function () {
  41357. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41358. serializationObject.customType = "BABYLON.PBRMaterial";
  41359. return serializationObject;
  41360. };
  41361. // Statics
  41362. /**
  41363. * Parses a PBR Material from a serialized object.
  41364. * @param source - Serialized object.
  41365. * @param scene - BJS scene instance.
  41366. * @param rootUrl - url for the scene object
  41367. * @returns - PBRMaterial
  41368. */
  41369. PBRMaterial.Parse = function (source, scene, rootUrl) {
  41370. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  41371. };
  41372. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  41373. /**
  41374. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41375. */
  41376. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  41377. /**
  41378. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41379. */
  41380. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  41381. /**
  41382. * 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.
  41383. * They are also discarded below the alpha cutoff threshold to improve performances.
  41384. */
  41385. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  41386. __decorate([
  41387. BABYLON.serialize(),
  41388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41389. ], PBRMaterial.prototype, "directIntensity", void 0);
  41390. __decorate([
  41391. BABYLON.serialize(),
  41392. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41393. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  41394. __decorate([
  41395. BABYLON.serialize(),
  41396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41397. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  41398. __decorate([
  41399. BABYLON.serialize(),
  41400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41401. ], PBRMaterial.prototype, "specularIntensity", void 0);
  41402. __decorate([
  41403. BABYLON.serialize(),
  41404. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41405. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  41406. __decorate([
  41407. BABYLON.serializeAsTexture(),
  41408. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41409. ], PBRMaterial.prototype, "albedoTexture", void 0);
  41410. __decorate([
  41411. BABYLON.serializeAsTexture(),
  41412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41413. ], PBRMaterial.prototype, "ambientTexture", void 0);
  41414. __decorate([
  41415. BABYLON.serialize(),
  41416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41417. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  41418. __decorate([
  41419. BABYLON.serializeAsTexture(),
  41420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41421. ], PBRMaterial.prototype, "opacityTexture", void 0);
  41422. __decorate([
  41423. BABYLON.serializeAsTexture(),
  41424. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41425. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  41426. __decorate([
  41427. BABYLON.serializeAsTexture(),
  41428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41429. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  41430. __decorate([
  41431. BABYLON.serializeAsTexture(),
  41432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41433. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  41434. __decorate([
  41435. BABYLON.serializeAsTexture(),
  41436. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41437. ], PBRMaterial.prototype, "metallicTexture", void 0);
  41438. __decorate([
  41439. BABYLON.serialize(),
  41440. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41441. ], PBRMaterial.prototype, "metallic", void 0);
  41442. __decorate([
  41443. BABYLON.serialize(),
  41444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41445. ], PBRMaterial.prototype, "roughness", void 0);
  41446. __decorate([
  41447. BABYLON.serializeAsTexture(),
  41448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41449. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  41450. __decorate([
  41451. BABYLON.serializeAsTexture(),
  41452. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41453. ], PBRMaterial.prototype, "bumpTexture", void 0);
  41454. __decorate([
  41455. BABYLON.serializeAsTexture(),
  41456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41457. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  41458. __decorate([
  41459. BABYLON.serializeAsTexture(),
  41460. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41461. ], PBRMaterial.prototype, "refractionTexture", void 0);
  41462. __decorate([
  41463. BABYLON.serializeAsColor3("ambient"),
  41464. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41465. ], PBRMaterial.prototype, "ambientColor", void 0);
  41466. __decorate([
  41467. BABYLON.serializeAsColor3("albedo"),
  41468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41469. ], PBRMaterial.prototype, "albedoColor", void 0);
  41470. __decorate([
  41471. BABYLON.serializeAsColor3("reflectivity"),
  41472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41473. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  41474. __decorate([
  41475. BABYLON.serializeAsColor3("reflection"),
  41476. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41477. ], PBRMaterial.prototype, "reflectionColor", void 0);
  41478. __decorate([
  41479. BABYLON.serializeAsColor3("emissive"),
  41480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41481. ], PBRMaterial.prototype, "emissiveColor", void 0);
  41482. __decorate([
  41483. BABYLON.serialize(),
  41484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41485. ], PBRMaterial.prototype, "microSurface", void 0);
  41486. __decorate([
  41487. BABYLON.serialize(),
  41488. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41489. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  41490. __decorate([
  41491. BABYLON.serialize(),
  41492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41493. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  41494. __decorate([
  41495. BABYLON.serialize(),
  41496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41497. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  41498. __decorate([
  41499. BABYLON.serialize(),
  41500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41501. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41502. __decorate([
  41503. BABYLON.serialize(),
  41504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41505. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  41506. __decorate([
  41507. BABYLON.serialize(),
  41508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41509. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  41510. __decorate([
  41511. BABYLON.serialize(),
  41512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41513. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  41514. __decorate([
  41515. BABYLON.serialize(),
  41516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41517. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  41518. __decorate([
  41519. BABYLON.serialize(),
  41520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41521. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  41522. __decorate([
  41523. BABYLON.serialize(),
  41524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41525. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  41526. __decorate([
  41527. BABYLON.serialize(),
  41528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41529. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  41530. __decorate([
  41531. BABYLON.serialize(),
  41532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41533. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  41534. __decorate([
  41535. BABYLON.serialize(),
  41536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41537. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  41538. __decorate([
  41539. BABYLON.serialize(),
  41540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41541. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  41542. __decorate([
  41543. BABYLON.serialize(),
  41544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41545. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  41546. __decorate([
  41547. BABYLON.serialize(),
  41548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41549. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  41550. __decorate([
  41551. BABYLON.serialize(),
  41552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41553. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  41554. __decorate([
  41555. BABYLON.serialize(),
  41556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41557. ], PBRMaterial.prototype, "useParallax", void 0);
  41558. __decorate([
  41559. BABYLON.serialize(),
  41560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41561. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  41562. __decorate([
  41563. BABYLON.serialize(),
  41564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41565. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  41566. __decorate([
  41567. BABYLON.serialize(),
  41568. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41569. ], PBRMaterial.prototype, "disableLighting", void 0);
  41570. __decorate([
  41571. BABYLON.serialize(),
  41572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41573. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  41574. __decorate([
  41575. BABYLON.serialize(),
  41576. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41577. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  41578. __decorate([
  41579. BABYLON.serialize(),
  41580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41581. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  41582. __decorate([
  41583. BABYLON.serialize(),
  41584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41585. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  41586. __decorate([
  41587. BABYLON.serialize(),
  41588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41589. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  41590. __decorate([
  41591. BABYLON.serialize(),
  41592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41593. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  41594. __decorate([
  41595. BABYLON.serialize(),
  41596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41597. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  41598. __decorate([
  41599. BABYLON.serializeAsTexture(),
  41600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41601. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  41602. __decorate([
  41603. BABYLON.serialize(),
  41604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41605. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  41606. __decorate([
  41607. BABYLON.serialize(),
  41608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41609. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  41610. __decorate([
  41611. BABYLON.serialize(),
  41612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41613. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  41614. return PBRMaterial;
  41615. }(BABYLON.PBRBaseMaterial));
  41616. BABYLON.PBRMaterial = PBRMaterial;
  41617. })(BABYLON || (BABYLON = {}));
  41618. //# sourceMappingURL=babylon.pbrMaterial.js.map
  41619. var BABYLON;
  41620. (function (BABYLON) {
  41621. /**
  41622. * The PBR material of BJS following the metal roughness convention.
  41623. *
  41624. * This fits to the PBR convention in the GLTF definition:
  41625. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  41626. */
  41627. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  41628. __extends(PBRMetallicRoughnessMaterial, _super);
  41629. /**
  41630. * Instantiates a new PBRMetalRoughnessMaterial instance.
  41631. *
  41632. * @param name The material name
  41633. * @param scene The scene the material will be use in.
  41634. */
  41635. function PBRMetallicRoughnessMaterial(name, scene) {
  41636. var _this = _super.call(this, name, scene) || this;
  41637. _this._useRoughnessFromMetallicTextureAlpha = false;
  41638. _this._useRoughnessFromMetallicTextureGreen = true;
  41639. _this._useMetallnessFromMetallicTextureBlue = true;
  41640. _this._forceMetallicWorkflow = true;
  41641. return _this;
  41642. }
  41643. /**
  41644. * Return the currrent class name of the material.
  41645. */
  41646. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  41647. return "PBRMetallicRoughnessMaterial";
  41648. };
  41649. /**
  41650. * Return the active textures of the material.
  41651. */
  41652. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  41653. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41654. if (this.baseTexture) {
  41655. activeTextures.push(this.baseTexture);
  41656. }
  41657. if (this.metallicRoughnessTexture) {
  41658. activeTextures.push(this.metallicRoughnessTexture);
  41659. }
  41660. return activeTextures;
  41661. };
  41662. /**
  41663. * Checks to see if a texture is used in the material.
  41664. * @param texture - Base texture to use.
  41665. * @returns - Boolean specifying if a texture is used in the material.
  41666. */
  41667. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  41668. if (_super.prototype.hasTexture.call(this, texture)) {
  41669. return true;
  41670. }
  41671. if (this.baseTexture === texture) {
  41672. return true;
  41673. }
  41674. if (this.metallicRoughnessTexture === texture) {
  41675. return true;
  41676. }
  41677. return false;
  41678. };
  41679. /**
  41680. * Makes a duplicate of the current material.
  41681. * @param name - name to use for the new material.
  41682. */
  41683. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  41684. var _this = this;
  41685. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  41686. clone.id = name;
  41687. clone.name = name;
  41688. return clone;
  41689. };
  41690. /**
  41691. * Serialize the material to a parsable JSON object.
  41692. */
  41693. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  41694. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41695. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  41696. return serializationObject;
  41697. };
  41698. /**
  41699. * Parses a JSON object correponding to the serialize function.
  41700. */
  41701. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  41702. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  41703. };
  41704. __decorate([
  41705. BABYLON.serializeAsColor3(),
  41706. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  41707. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  41708. __decorate([
  41709. BABYLON.serializeAsTexture(),
  41710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  41711. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  41712. __decorate([
  41713. BABYLON.serialize(),
  41714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41715. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  41716. __decorate([
  41717. BABYLON.serialize(),
  41718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41719. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  41720. __decorate([
  41721. BABYLON.serializeAsTexture(),
  41722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  41723. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  41724. return PBRMetallicRoughnessMaterial;
  41725. }(BABYLON.PBRBaseSimpleMaterial));
  41726. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  41727. })(BABYLON || (BABYLON = {}));
  41728. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  41729. var BABYLON;
  41730. (function (BABYLON) {
  41731. /**
  41732. * The PBR material of BJS following the specular glossiness convention.
  41733. *
  41734. * This fits to the PBR convention in the GLTF definition:
  41735. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  41736. */
  41737. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  41738. __extends(PBRSpecularGlossinessMaterial, _super);
  41739. /**
  41740. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  41741. *
  41742. * @param name The material name
  41743. * @param scene The scene the material will be use in.
  41744. */
  41745. function PBRSpecularGlossinessMaterial(name, scene) {
  41746. var _this = _super.call(this, name, scene) || this;
  41747. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  41748. return _this;
  41749. }
  41750. /**
  41751. * Return the currrent class name of the material.
  41752. */
  41753. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  41754. return "PBRSpecularGlossinessMaterial";
  41755. };
  41756. /**
  41757. * Return the active textures of the material.
  41758. */
  41759. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  41760. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41761. if (this.diffuseTexture) {
  41762. activeTextures.push(this.diffuseTexture);
  41763. }
  41764. if (this.specularGlossinessTexture) {
  41765. activeTextures.push(this.specularGlossinessTexture);
  41766. }
  41767. return activeTextures;
  41768. };
  41769. /**
  41770. * Checks to see if a texture is used in the material.
  41771. * @param texture - Base texture to use.
  41772. * @returns - Boolean specifying if a texture is used in the material.
  41773. */
  41774. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  41775. if (_super.prototype.hasTexture.call(this, texture)) {
  41776. return true;
  41777. }
  41778. if (this.diffuseTexture === texture) {
  41779. return true;
  41780. }
  41781. if (this.specularGlossinessTexture === texture) {
  41782. return true;
  41783. }
  41784. return false;
  41785. };
  41786. /**
  41787. * Makes a duplicate of the current material.
  41788. * @param name - name to use for the new material.
  41789. */
  41790. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  41791. var _this = this;
  41792. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  41793. clone.id = name;
  41794. clone.name = name;
  41795. return clone;
  41796. };
  41797. /**
  41798. * Serialize the material to a parsable JSON object.
  41799. */
  41800. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  41801. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41802. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  41803. return serializationObject;
  41804. };
  41805. /**
  41806. * Parses a JSON object correponding to the serialize function.
  41807. */
  41808. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  41809. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  41810. };
  41811. __decorate([
  41812. BABYLON.serializeAsColor3("diffuse"),
  41813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  41814. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  41815. __decorate([
  41816. BABYLON.serializeAsTexture(),
  41817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  41818. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  41819. __decorate([
  41820. BABYLON.serializeAsColor3("specular"),
  41821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  41822. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  41823. __decorate([
  41824. BABYLON.serialize(),
  41825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  41826. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  41827. __decorate([
  41828. BABYLON.serializeAsTexture(),
  41829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  41830. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  41831. return PBRSpecularGlossinessMaterial;
  41832. }(BABYLON.PBRBaseSimpleMaterial));
  41833. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  41834. })(BABYLON || (BABYLON = {}));
  41835. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  41836. var BABYLON;
  41837. (function (BABYLON) {
  41838. BABYLON.CameraInputTypes = {};
  41839. var CameraInputsManager = /** @class */ (function () {
  41840. function CameraInputsManager(camera) {
  41841. this.attached = {};
  41842. this.camera = camera;
  41843. this.checkInputs = function () { };
  41844. }
  41845. /**
  41846. * Add an input method to a camera.
  41847. * builtin inputs example: camera.inputs.addGamepad();
  41848. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  41849. * @param input camera input method
  41850. */
  41851. CameraInputsManager.prototype.add = function (input) {
  41852. var type = input.getSimpleName();
  41853. if (this.attached[type]) {
  41854. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  41855. return;
  41856. }
  41857. this.attached[type] = input;
  41858. input.camera = this.camera;
  41859. //for checkInputs, we are dynamically creating a function
  41860. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  41861. if (input.checkInputs) {
  41862. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  41863. }
  41864. if (this.attachedElement) {
  41865. input.attachControl(this.attachedElement);
  41866. }
  41867. };
  41868. /**
  41869. * Remove a specific input method from a camera
  41870. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  41871. * @param inputToRemove camera input method
  41872. */
  41873. CameraInputsManager.prototype.remove = function (inputToRemove) {
  41874. for (var cam in this.attached) {
  41875. var input = this.attached[cam];
  41876. if (input === inputToRemove) {
  41877. input.detachControl(this.attachedElement);
  41878. input.camera = null;
  41879. delete this.attached[cam];
  41880. this.rebuildInputCheck();
  41881. }
  41882. }
  41883. };
  41884. CameraInputsManager.prototype.removeByType = function (inputType) {
  41885. for (var cam in this.attached) {
  41886. var input = this.attached[cam];
  41887. if (input.getClassName() === inputType) {
  41888. input.detachControl(this.attachedElement);
  41889. input.camera = null;
  41890. delete this.attached[cam];
  41891. this.rebuildInputCheck();
  41892. }
  41893. }
  41894. };
  41895. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  41896. var current = this.checkInputs;
  41897. return function () {
  41898. current();
  41899. fn();
  41900. };
  41901. };
  41902. CameraInputsManager.prototype.attachInput = function (input) {
  41903. if (this.attachedElement) {
  41904. input.attachControl(this.attachedElement, this.noPreventDefault);
  41905. }
  41906. };
  41907. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  41908. if (noPreventDefault === void 0) { noPreventDefault = false; }
  41909. if (this.attachedElement) {
  41910. return;
  41911. }
  41912. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  41913. this.attachedElement = element;
  41914. this.noPreventDefault = noPreventDefault;
  41915. for (var cam in this.attached) {
  41916. this.attached[cam].attachControl(element, noPreventDefault);
  41917. }
  41918. };
  41919. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  41920. if (disconnect === void 0) { disconnect = false; }
  41921. if (this.attachedElement !== element) {
  41922. return;
  41923. }
  41924. for (var cam in this.attached) {
  41925. this.attached[cam].detachControl(element);
  41926. if (disconnect) {
  41927. this.attached[cam].camera = null;
  41928. }
  41929. }
  41930. this.attachedElement = null;
  41931. };
  41932. CameraInputsManager.prototype.rebuildInputCheck = function () {
  41933. this.checkInputs = function () { };
  41934. for (var cam in this.attached) {
  41935. var input = this.attached[cam];
  41936. if (input.checkInputs) {
  41937. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  41938. }
  41939. }
  41940. };
  41941. /**
  41942. * Remove all attached input methods from a camera
  41943. */
  41944. CameraInputsManager.prototype.clear = function () {
  41945. if (this.attachedElement) {
  41946. this.detachElement(this.attachedElement, true);
  41947. }
  41948. this.attached = {};
  41949. this.attachedElement = null;
  41950. this.checkInputs = function () { };
  41951. };
  41952. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  41953. var inputs = {};
  41954. for (var cam in this.attached) {
  41955. var input = this.attached[cam];
  41956. var res = BABYLON.SerializationHelper.Serialize(input);
  41957. inputs[input.getClassName()] = res;
  41958. }
  41959. serializedCamera.inputsmgr = inputs;
  41960. };
  41961. CameraInputsManager.prototype.parse = function (parsedCamera) {
  41962. var parsedInputs = parsedCamera.inputsmgr;
  41963. if (parsedInputs) {
  41964. this.clear();
  41965. for (var n in parsedInputs) {
  41966. var construct = BABYLON.CameraInputTypes[n];
  41967. if (construct) {
  41968. var parsedinput = parsedInputs[n];
  41969. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  41970. this.add(input);
  41971. }
  41972. }
  41973. }
  41974. else {
  41975. //2016-03-08 this part is for managing backward compatibility
  41976. for (var n in this.attached) {
  41977. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  41978. if (construct) {
  41979. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  41980. this.remove(this.attached[n]);
  41981. this.add(input);
  41982. }
  41983. }
  41984. }
  41985. };
  41986. return CameraInputsManager;
  41987. }());
  41988. BABYLON.CameraInputsManager = CameraInputsManager;
  41989. })(BABYLON || (BABYLON = {}));
  41990. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  41991. var BABYLON;
  41992. (function (BABYLON) {
  41993. var TargetCamera = /** @class */ (function (_super) {
  41994. __extends(TargetCamera, _super);
  41995. function TargetCamera(name, position, scene) {
  41996. var _this = _super.call(this, name, position, scene) || this;
  41997. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  41998. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  41999. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  42000. _this.speed = 2.0;
  42001. _this.noRotationConstraint = false;
  42002. _this.lockedTarget = null;
  42003. _this._currentTarget = BABYLON.Vector3.Zero();
  42004. _this._viewMatrix = BABYLON.Matrix.Zero();
  42005. _this._camMatrix = BABYLON.Matrix.Zero();
  42006. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  42007. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  42008. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  42009. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  42010. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  42011. _this._lookAtTemp = BABYLON.Matrix.Zero();
  42012. _this._tempMatrix = BABYLON.Matrix.Zero();
  42013. return _this;
  42014. }
  42015. TargetCamera.prototype.getFrontPosition = function (distance) {
  42016. this.getWorldMatrix();
  42017. var direction = this.getTarget().subtract(this.position);
  42018. direction.normalize();
  42019. direction.scaleInPlace(distance);
  42020. return this.globalPosition.add(direction);
  42021. };
  42022. TargetCamera.prototype._getLockedTargetPosition = function () {
  42023. if (!this.lockedTarget) {
  42024. return null;
  42025. }
  42026. if (this.lockedTarget.absolutePosition) {
  42027. this.lockedTarget.computeWorldMatrix();
  42028. }
  42029. return this.lockedTarget.absolutePosition || this.lockedTarget;
  42030. };
  42031. TargetCamera.prototype.storeState = function () {
  42032. this._storedPosition = this.position.clone();
  42033. this._storedRotation = this.rotation.clone();
  42034. if (this.rotationQuaternion) {
  42035. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  42036. }
  42037. return _super.prototype.storeState.call(this);
  42038. };
  42039. /**
  42040. * Restored camera state. You must call storeState() first
  42041. */
  42042. TargetCamera.prototype._restoreStateValues = function () {
  42043. if (!_super.prototype._restoreStateValues.call(this)) {
  42044. return false;
  42045. }
  42046. this.position = this._storedPosition.clone();
  42047. this.rotation = this._storedRotation.clone();
  42048. if (this.rotationQuaternion) {
  42049. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  42050. }
  42051. this.cameraDirection.copyFromFloats(0, 0, 0);
  42052. this.cameraRotation.copyFromFloats(0, 0);
  42053. return true;
  42054. };
  42055. // Cache
  42056. TargetCamera.prototype._initCache = function () {
  42057. _super.prototype._initCache.call(this);
  42058. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42059. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42060. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42061. };
  42062. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  42063. if (!ignoreParentClass) {
  42064. _super.prototype._updateCache.call(this);
  42065. }
  42066. var lockedTargetPosition = this._getLockedTargetPosition();
  42067. if (!lockedTargetPosition) {
  42068. this._cache.lockedTarget = null;
  42069. }
  42070. else {
  42071. if (!this._cache.lockedTarget) {
  42072. this._cache.lockedTarget = lockedTargetPosition.clone();
  42073. }
  42074. else {
  42075. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  42076. }
  42077. }
  42078. this._cache.rotation.copyFrom(this.rotation);
  42079. if (this.rotationQuaternion)
  42080. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42081. };
  42082. // Synchronized
  42083. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  42084. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  42085. return false;
  42086. }
  42087. var lockedTargetPosition = this._getLockedTargetPosition();
  42088. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  42089. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  42090. };
  42091. // Methods
  42092. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  42093. var engine = this.getEngine();
  42094. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  42095. };
  42096. // Target
  42097. TargetCamera.prototype.setTarget = function (target) {
  42098. this.upVector.normalize();
  42099. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  42100. this._camMatrix.invert();
  42101. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  42102. var vDir = target.subtract(this.position);
  42103. if (vDir.x >= 0.0) {
  42104. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  42105. }
  42106. else {
  42107. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  42108. }
  42109. this.rotation.z = 0;
  42110. if (isNaN(this.rotation.x)) {
  42111. this.rotation.x = 0;
  42112. }
  42113. if (isNaN(this.rotation.y)) {
  42114. this.rotation.y = 0;
  42115. }
  42116. if (isNaN(this.rotation.z)) {
  42117. this.rotation.z = 0;
  42118. }
  42119. if (this.rotationQuaternion) {
  42120. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42121. }
  42122. };
  42123. /**
  42124. * Return the current target position of the camera. This value is expressed in local space.
  42125. */
  42126. TargetCamera.prototype.getTarget = function () {
  42127. return this._currentTarget;
  42128. };
  42129. TargetCamera.prototype._decideIfNeedsToMove = function () {
  42130. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  42131. };
  42132. TargetCamera.prototype._updatePosition = function () {
  42133. if (this.parent) {
  42134. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  42135. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  42136. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  42137. return;
  42138. }
  42139. this.position.addInPlace(this.cameraDirection);
  42140. };
  42141. TargetCamera.prototype._checkInputs = function () {
  42142. var needToMove = this._decideIfNeedsToMove();
  42143. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  42144. // Move
  42145. if (needToMove) {
  42146. this._updatePosition();
  42147. }
  42148. // Rotate
  42149. if (needToRotate) {
  42150. this.rotation.x += this.cameraRotation.x;
  42151. this.rotation.y += this.cameraRotation.y;
  42152. //rotate, if quaternion is set and rotation was used
  42153. if (this.rotationQuaternion) {
  42154. var len = this.rotation.lengthSquared();
  42155. if (len) {
  42156. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42157. }
  42158. }
  42159. if (!this.noRotationConstraint) {
  42160. var limit = (Math.PI / 2) * 0.95;
  42161. if (this.rotation.x > limit)
  42162. this.rotation.x = limit;
  42163. if (this.rotation.x < -limit)
  42164. this.rotation.x = -limit;
  42165. }
  42166. }
  42167. // Inertia
  42168. if (needToMove) {
  42169. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  42170. this.cameraDirection.x = 0;
  42171. }
  42172. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  42173. this.cameraDirection.y = 0;
  42174. }
  42175. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  42176. this.cameraDirection.z = 0;
  42177. }
  42178. this.cameraDirection.scaleInPlace(this.inertia);
  42179. }
  42180. if (needToRotate) {
  42181. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  42182. this.cameraRotation.x = 0;
  42183. }
  42184. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  42185. this.cameraRotation.y = 0;
  42186. }
  42187. this.cameraRotation.scaleInPlace(this.inertia);
  42188. }
  42189. _super.prototype._checkInputs.call(this);
  42190. };
  42191. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  42192. if (this.rotationQuaternion) {
  42193. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  42194. }
  42195. else {
  42196. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  42197. }
  42198. //update the up vector!
  42199. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  42200. };
  42201. TargetCamera.prototype._getViewMatrix = function () {
  42202. if (this.lockedTarget) {
  42203. this.setTarget(this._getLockedTargetPosition());
  42204. }
  42205. // Compute
  42206. this._updateCameraRotationMatrix();
  42207. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  42208. // Computing target and final matrix
  42209. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  42210. if (this.getScene().useRightHandedSystem) {
  42211. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42212. }
  42213. else {
  42214. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42215. }
  42216. return this._viewMatrix;
  42217. };
  42218. /**
  42219. * @override
  42220. * Override Camera.createRigCamera
  42221. */
  42222. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  42223. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  42224. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  42225. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  42226. if (!this.rotationQuaternion) {
  42227. this.rotationQuaternion = new BABYLON.Quaternion();
  42228. }
  42229. rigCamera._cameraRigParams = {};
  42230. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  42231. }
  42232. return rigCamera;
  42233. }
  42234. return null;
  42235. };
  42236. /**
  42237. * @override
  42238. * Override Camera._updateRigCameras
  42239. */
  42240. TargetCamera.prototype._updateRigCameras = function () {
  42241. var camLeft = this._rigCameras[0];
  42242. var camRight = this._rigCameras[1];
  42243. switch (this.cameraRigMode) {
  42244. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42245. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42246. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42247. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42248. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  42249. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  42250. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  42251. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  42252. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  42253. camLeft.setTarget(this.getTarget());
  42254. camRight.setTarget(this.getTarget());
  42255. break;
  42256. case BABYLON.Camera.RIG_MODE_VR:
  42257. if (camLeft.rotationQuaternion) {
  42258. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42259. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42260. }
  42261. else {
  42262. camLeft.rotation.copyFrom(this.rotation);
  42263. camRight.rotation.copyFrom(this.rotation);
  42264. }
  42265. camLeft.position.copyFrom(this.position);
  42266. camRight.position.copyFrom(this.position);
  42267. break;
  42268. }
  42269. _super.prototype._updateRigCameras.call(this);
  42270. };
  42271. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  42272. if (!this._rigCamTransformMatrix) {
  42273. this._rigCamTransformMatrix = new BABYLON.Matrix();
  42274. }
  42275. var target = this.getTarget();
  42276. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  42277. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  42278. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  42279. };
  42280. TargetCamera.prototype.getClassName = function () {
  42281. return "TargetCamera";
  42282. };
  42283. __decorate([
  42284. BABYLON.serializeAsVector3()
  42285. ], TargetCamera.prototype, "rotation", void 0);
  42286. __decorate([
  42287. BABYLON.serialize()
  42288. ], TargetCamera.prototype, "speed", void 0);
  42289. __decorate([
  42290. BABYLON.serializeAsMeshReference("lockedTargetId")
  42291. ], TargetCamera.prototype, "lockedTarget", void 0);
  42292. return TargetCamera;
  42293. }(BABYLON.Camera));
  42294. BABYLON.TargetCamera = TargetCamera;
  42295. })(BABYLON || (BABYLON = {}));
  42296. //# sourceMappingURL=babylon.targetCamera.js.map
  42297. var BABYLON;
  42298. (function (BABYLON) {
  42299. var FreeCameraMouseInput = /** @class */ (function () {
  42300. function FreeCameraMouseInput(touchEnabled) {
  42301. if (touchEnabled === void 0) { touchEnabled = true; }
  42302. this.touchEnabled = touchEnabled;
  42303. this.buttons = [0, 1, 2];
  42304. this.angularSensibility = 2000.0;
  42305. this.previousPosition = null;
  42306. }
  42307. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  42308. var _this = this;
  42309. var engine = this.camera.getEngine();
  42310. if (!this._pointerInput) {
  42311. this._pointerInput = function (p, s) {
  42312. var evt = p.event;
  42313. if (engine.isInVRExclusivePointerMode) {
  42314. return;
  42315. }
  42316. if (!_this.touchEnabled && evt.pointerType === "touch") {
  42317. return;
  42318. }
  42319. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  42320. return;
  42321. }
  42322. var srcElement = (evt.srcElement || evt.target);
  42323. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  42324. try {
  42325. srcElement.setPointerCapture(evt.pointerId);
  42326. }
  42327. catch (e) {
  42328. //Nothing to do with the error. Execution will continue.
  42329. }
  42330. _this.previousPosition = {
  42331. x: evt.clientX,
  42332. y: evt.clientY
  42333. };
  42334. if (!noPreventDefault) {
  42335. evt.preventDefault();
  42336. element.focus();
  42337. }
  42338. }
  42339. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  42340. try {
  42341. srcElement.releasePointerCapture(evt.pointerId);
  42342. }
  42343. catch (e) {
  42344. //Nothing to do with the error.
  42345. }
  42346. _this.previousPosition = null;
  42347. if (!noPreventDefault) {
  42348. evt.preventDefault();
  42349. }
  42350. }
  42351. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  42352. if (!_this.previousPosition || engine.isPointerLock) {
  42353. return;
  42354. }
  42355. var offsetX = evt.clientX - _this.previousPosition.x;
  42356. var offsetY = evt.clientY - _this.previousPosition.y;
  42357. if (_this.camera.getScene().useRightHandedSystem) {
  42358. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42359. }
  42360. else {
  42361. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  42362. }
  42363. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  42364. _this.previousPosition = {
  42365. x: evt.clientX,
  42366. y: evt.clientY
  42367. };
  42368. if (!noPreventDefault) {
  42369. evt.preventDefault();
  42370. }
  42371. }
  42372. };
  42373. }
  42374. this._onMouseMove = function (evt) {
  42375. if (!engine.isPointerLock) {
  42376. return;
  42377. }
  42378. if (engine.isInVRExclusivePointerMode) {
  42379. return;
  42380. }
  42381. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  42382. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  42383. if (_this.camera.getScene().useRightHandedSystem) {
  42384. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42385. }
  42386. else {
  42387. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  42388. }
  42389. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  42390. _this.previousPosition = null;
  42391. if (!noPreventDefault) {
  42392. evt.preventDefault();
  42393. }
  42394. };
  42395. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  42396. element.addEventListener("mousemove", this._onMouseMove, false);
  42397. };
  42398. FreeCameraMouseInput.prototype.detachControl = function (element) {
  42399. if (this._observer && element) {
  42400. this.camera.getScene().onPointerObservable.remove(this._observer);
  42401. if (this._onMouseMove) {
  42402. element.removeEventListener("mousemove", this._onMouseMove);
  42403. }
  42404. this._observer = null;
  42405. this._onMouseMove = null;
  42406. this.previousPosition = null;
  42407. }
  42408. };
  42409. FreeCameraMouseInput.prototype.getClassName = function () {
  42410. return "FreeCameraMouseInput";
  42411. };
  42412. FreeCameraMouseInput.prototype.getSimpleName = function () {
  42413. return "mouse";
  42414. };
  42415. __decorate([
  42416. BABYLON.serialize()
  42417. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  42418. __decorate([
  42419. BABYLON.serialize()
  42420. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  42421. return FreeCameraMouseInput;
  42422. }());
  42423. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  42424. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  42425. })(BABYLON || (BABYLON = {}));
  42426. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  42427. var BABYLON;
  42428. (function (BABYLON) {
  42429. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  42430. function FreeCameraKeyboardMoveInput() {
  42431. this._keys = new Array();
  42432. this.keysUp = [38];
  42433. this.keysDown = [40];
  42434. this.keysLeft = [37];
  42435. this.keysRight = [39];
  42436. }
  42437. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  42438. var _this = this;
  42439. if (this._onCanvasBlurObserver) {
  42440. return;
  42441. }
  42442. this._scene = this.camera.getScene();
  42443. this._engine = this._scene.getEngine();
  42444. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  42445. _this._keys = [];
  42446. });
  42447. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  42448. var evt = info.event;
  42449. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  42450. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  42451. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  42452. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  42453. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  42454. var index = _this._keys.indexOf(evt.keyCode);
  42455. if (index === -1) {
  42456. _this._keys.push(evt.keyCode);
  42457. }
  42458. if (!noPreventDefault) {
  42459. evt.preventDefault();
  42460. }
  42461. }
  42462. }
  42463. else {
  42464. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  42465. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  42466. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  42467. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  42468. var index = _this._keys.indexOf(evt.keyCode);
  42469. if (index >= 0) {
  42470. _this._keys.splice(index, 1);
  42471. }
  42472. if (!noPreventDefault) {
  42473. evt.preventDefault();
  42474. }
  42475. }
  42476. }
  42477. });
  42478. };
  42479. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  42480. if (this._scene) {
  42481. if (this._onKeyboardObserver) {
  42482. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  42483. }
  42484. if (this._onCanvasBlurObserver) {
  42485. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  42486. }
  42487. this._onKeyboardObserver = null;
  42488. this._onCanvasBlurObserver = null;
  42489. }
  42490. this._keys = [];
  42491. };
  42492. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  42493. if (this._onKeyboardObserver) {
  42494. var camera = this.camera;
  42495. // Keyboard
  42496. for (var index = 0; index < this._keys.length; index++) {
  42497. var keyCode = this._keys[index];
  42498. var speed = camera._computeLocalCameraSpeed();
  42499. if (this.keysLeft.indexOf(keyCode) !== -1) {
  42500. camera._localDirection.copyFromFloats(-speed, 0, 0);
  42501. }
  42502. else if (this.keysUp.indexOf(keyCode) !== -1) {
  42503. camera._localDirection.copyFromFloats(0, 0, speed);
  42504. }
  42505. else if (this.keysRight.indexOf(keyCode) !== -1) {
  42506. camera._localDirection.copyFromFloats(speed, 0, 0);
  42507. }
  42508. else if (this.keysDown.indexOf(keyCode) !== -1) {
  42509. camera._localDirection.copyFromFloats(0, 0, -speed);
  42510. }
  42511. if (camera.getScene().useRightHandedSystem) {
  42512. camera._localDirection.z *= -1;
  42513. }
  42514. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  42515. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  42516. camera.cameraDirection.addInPlace(camera._transformedDirection);
  42517. }
  42518. }
  42519. };
  42520. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  42521. return "FreeCameraKeyboardMoveInput";
  42522. };
  42523. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  42524. this._keys = [];
  42525. };
  42526. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  42527. return "keyboard";
  42528. };
  42529. __decorate([
  42530. BABYLON.serialize()
  42531. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  42532. __decorate([
  42533. BABYLON.serialize()
  42534. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  42535. __decorate([
  42536. BABYLON.serialize()
  42537. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  42538. __decorate([
  42539. BABYLON.serialize()
  42540. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  42541. return FreeCameraKeyboardMoveInput;
  42542. }());
  42543. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  42544. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  42545. })(BABYLON || (BABYLON = {}));
  42546. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  42547. var BABYLON;
  42548. (function (BABYLON) {
  42549. var FreeCameraInputsManager = /** @class */ (function (_super) {
  42550. __extends(FreeCameraInputsManager, _super);
  42551. function FreeCameraInputsManager(camera) {
  42552. return _super.call(this, camera) || this;
  42553. }
  42554. FreeCameraInputsManager.prototype.addKeyboard = function () {
  42555. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  42556. return this;
  42557. };
  42558. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  42559. if (touchEnabled === void 0) { touchEnabled = true; }
  42560. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  42561. return this;
  42562. };
  42563. FreeCameraInputsManager.prototype.addGamepad = function () {
  42564. this.add(new BABYLON.FreeCameraGamepadInput());
  42565. return this;
  42566. };
  42567. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  42568. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  42569. return this;
  42570. };
  42571. FreeCameraInputsManager.prototype.addTouch = function () {
  42572. this.add(new BABYLON.FreeCameraTouchInput());
  42573. return this;
  42574. };
  42575. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  42576. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  42577. return this;
  42578. };
  42579. return FreeCameraInputsManager;
  42580. }(BABYLON.CameraInputsManager));
  42581. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  42582. })(BABYLON || (BABYLON = {}));
  42583. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  42584. var BABYLON;
  42585. (function (BABYLON) {
  42586. var FreeCamera = /** @class */ (function (_super) {
  42587. __extends(FreeCamera, _super);
  42588. function FreeCamera(name, position, scene) {
  42589. var _this = _super.call(this, name, position, scene) || this;
  42590. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  42591. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  42592. _this.checkCollisions = false;
  42593. _this.applyGravity = false;
  42594. _this._needMoveForGravity = false;
  42595. _this._oldPosition = BABYLON.Vector3.Zero();
  42596. _this._diffPosition = BABYLON.Vector3.Zero();
  42597. _this._newPosition = BABYLON.Vector3.Zero();
  42598. // Collisions
  42599. _this._collisionMask = -1;
  42600. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  42601. if (collidedMesh === void 0) { collidedMesh = null; }
  42602. //TODO move this to the collision coordinator!
  42603. if (_this.getScene().workerCollisions)
  42604. newPosition.multiplyInPlace(_this._collider._radius);
  42605. var updatePosition = function (newPos) {
  42606. _this._newPosition.copyFrom(newPos);
  42607. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  42608. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  42609. _this.position.addInPlace(_this._diffPosition);
  42610. if (_this.onCollide && collidedMesh) {
  42611. _this.onCollide(collidedMesh);
  42612. }
  42613. }
  42614. };
  42615. updatePosition(newPosition);
  42616. };
  42617. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  42618. _this.inputs.addKeyboard().addMouse();
  42619. return _this;
  42620. }
  42621. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  42622. //-- begin properties for backward compatibility for inputs
  42623. /**
  42624. * Gets the input sensibility for a mouse input. (default is 2000.0)
  42625. * Higher values reduce sensitivity.
  42626. */
  42627. get: function () {
  42628. var mouse = this.inputs.attached["mouse"];
  42629. if (mouse)
  42630. return mouse.angularSensibility;
  42631. return 0;
  42632. },
  42633. /**
  42634. * Sets the input sensibility for a mouse input. (default is 2000.0)
  42635. * Higher values reduce sensitivity.
  42636. */
  42637. set: function (value) {
  42638. var mouse = this.inputs.attached["mouse"];
  42639. if (mouse)
  42640. mouse.angularSensibility = value;
  42641. },
  42642. enumerable: true,
  42643. configurable: true
  42644. });
  42645. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  42646. get: function () {
  42647. var keyboard = this.inputs.attached["keyboard"];
  42648. if (keyboard)
  42649. return keyboard.keysUp;
  42650. return [];
  42651. },
  42652. set: function (value) {
  42653. var keyboard = this.inputs.attached["keyboard"];
  42654. if (keyboard)
  42655. keyboard.keysUp = value;
  42656. },
  42657. enumerable: true,
  42658. configurable: true
  42659. });
  42660. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  42661. get: function () {
  42662. var keyboard = this.inputs.attached["keyboard"];
  42663. if (keyboard)
  42664. return keyboard.keysDown;
  42665. return [];
  42666. },
  42667. set: function (value) {
  42668. var keyboard = this.inputs.attached["keyboard"];
  42669. if (keyboard)
  42670. keyboard.keysDown = value;
  42671. },
  42672. enumerable: true,
  42673. configurable: true
  42674. });
  42675. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  42676. get: function () {
  42677. var keyboard = this.inputs.attached["keyboard"];
  42678. if (keyboard)
  42679. return keyboard.keysLeft;
  42680. return [];
  42681. },
  42682. set: function (value) {
  42683. var keyboard = this.inputs.attached["keyboard"];
  42684. if (keyboard)
  42685. keyboard.keysLeft = value;
  42686. },
  42687. enumerable: true,
  42688. configurable: true
  42689. });
  42690. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  42691. get: function () {
  42692. var keyboard = this.inputs.attached["keyboard"];
  42693. if (keyboard)
  42694. return keyboard.keysRight;
  42695. return [];
  42696. },
  42697. set: function (value) {
  42698. var keyboard = this.inputs.attached["keyboard"];
  42699. if (keyboard)
  42700. keyboard.keysRight = value;
  42701. },
  42702. enumerable: true,
  42703. configurable: true
  42704. });
  42705. // Controls
  42706. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  42707. this.inputs.attachElement(element, noPreventDefault);
  42708. };
  42709. FreeCamera.prototype.detachControl = function (element) {
  42710. this.inputs.detachElement(element);
  42711. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  42712. this.cameraRotation = new BABYLON.Vector2(0, 0);
  42713. };
  42714. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  42715. get: function () {
  42716. return this._collisionMask;
  42717. },
  42718. set: function (mask) {
  42719. this._collisionMask = !isNaN(mask) ? mask : -1;
  42720. },
  42721. enumerable: true,
  42722. configurable: true
  42723. });
  42724. FreeCamera.prototype._collideWithWorld = function (displacement) {
  42725. var globalPosition;
  42726. if (this.parent) {
  42727. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  42728. }
  42729. else {
  42730. globalPosition = this.position;
  42731. }
  42732. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  42733. this._oldPosition.addInPlace(this.ellipsoidOffset);
  42734. if (!this._collider) {
  42735. this._collider = new BABYLON.Collider();
  42736. }
  42737. this._collider._radius = this.ellipsoid;
  42738. this._collider.collisionMask = this._collisionMask;
  42739. //no need for clone, as long as gravity is not on.
  42740. var actualDisplacement = displacement;
  42741. //add gravity to the direction to prevent the dual-collision checking
  42742. if (this.applyGravity) {
  42743. //this prevents mending with cameraDirection, a global variable of the free camera class.
  42744. actualDisplacement = displacement.add(this.getScene().gravity);
  42745. }
  42746. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  42747. };
  42748. FreeCamera.prototype._checkInputs = function () {
  42749. if (!this._localDirection) {
  42750. this._localDirection = BABYLON.Vector3.Zero();
  42751. this._transformedDirection = BABYLON.Vector3.Zero();
  42752. }
  42753. this.inputs.checkInputs();
  42754. _super.prototype._checkInputs.call(this);
  42755. };
  42756. FreeCamera.prototype._decideIfNeedsToMove = function () {
  42757. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  42758. };
  42759. FreeCamera.prototype._updatePosition = function () {
  42760. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  42761. this._collideWithWorld(this.cameraDirection);
  42762. }
  42763. else {
  42764. _super.prototype._updatePosition.call(this);
  42765. }
  42766. };
  42767. FreeCamera.prototype.dispose = function () {
  42768. this.inputs.clear();
  42769. _super.prototype.dispose.call(this);
  42770. };
  42771. FreeCamera.prototype.getClassName = function () {
  42772. return "FreeCamera";
  42773. };
  42774. __decorate([
  42775. BABYLON.serializeAsVector3()
  42776. ], FreeCamera.prototype, "ellipsoid", void 0);
  42777. __decorate([
  42778. BABYLON.serializeAsVector3()
  42779. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  42780. __decorate([
  42781. BABYLON.serialize()
  42782. ], FreeCamera.prototype, "checkCollisions", void 0);
  42783. __decorate([
  42784. BABYLON.serialize()
  42785. ], FreeCamera.prototype, "applyGravity", void 0);
  42786. return FreeCamera;
  42787. }(BABYLON.TargetCamera));
  42788. BABYLON.FreeCamera = FreeCamera;
  42789. })(BABYLON || (BABYLON = {}));
  42790. //# sourceMappingURL=babylon.freeCamera.js.map
  42791. var BABYLON;
  42792. (function (BABYLON) {
  42793. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  42794. function ArcRotateCameraKeyboardMoveInput() {
  42795. this._keys = new Array();
  42796. this.keysUp = [38];
  42797. this.keysDown = [40];
  42798. this.keysLeft = [37];
  42799. this.keysRight = [39];
  42800. this.keysReset = [220];
  42801. this.panningSensibility = 50.0;
  42802. this.zoomingSensibility = 25.0;
  42803. this.useAltToZoom = true;
  42804. }
  42805. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  42806. var _this = this;
  42807. if (this._onCanvasBlurObserver) {
  42808. return;
  42809. }
  42810. this._scene = this.camera.getScene();
  42811. this._engine = this._scene.getEngine();
  42812. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  42813. _this._keys = [];
  42814. });
  42815. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  42816. var evt = info.event;
  42817. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  42818. _this._ctrlPressed = evt.ctrlKey;
  42819. _this._altPressed = evt.altKey;
  42820. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  42821. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  42822. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  42823. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  42824. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  42825. var index = _this._keys.indexOf(evt.keyCode);
  42826. if (index === -1) {
  42827. _this._keys.push(evt.keyCode);
  42828. }
  42829. if (evt.preventDefault) {
  42830. if (!noPreventDefault) {
  42831. evt.preventDefault();
  42832. }
  42833. }
  42834. }
  42835. }
  42836. else {
  42837. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  42838. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  42839. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  42840. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  42841. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  42842. var index = _this._keys.indexOf(evt.keyCode);
  42843. if (index >= 0) {
  42844. _this._keys.splice(index, 1);
  42845. }
  42846. if (evt.preventDefault) {
  42847. if (!noPreventDefault) {
  42848. evt.preventDefault();
  42849. }
  42850. }
  42851. }
  42852. }
  42853. });
  42854. };
  42855. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  42856. if (this._scene) {
  42857. if (this._onKeyboardObserver) {
  42858. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  42859. }
  42860. if (this._onCanvasBlurObserver) {
  42861. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  42862. }
  42863. this._onKeyboardObserver = null;
  42864. this._onCanvasBlurObserver = null;
  42865. }
  42866. this._keys = [];
  42867. };
  42868. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  42869. if (this._onKeyboardObserver) {
  42870. var camera = this.camera;
  42871. for (var index = 0; index < this._keys.length; index++) {
  42872. var keyCode = this._keys[index];
  42873. if (this.keysLeft.indexOf(keyCode) !== -1) {
  42874. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  42875. camera.inertialPanningX -= 1 / this.panningSensibility;
  42876. }
  42877. else {
  42878. camera.inertialAlphaOffset -= 0.01;
  42879. }
  42880. }
  42881. else if (this.keysUp.indexOf(keyCode) !== -1) {
  42882. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  42883. camera.inertialPanningY += 1 / this.panningSensibility;
  42884. }
  42885. else if (this._altPressed && this.useAltToZoom) {
  42886. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  42887. }
  42888. else {
  42889. camera.inertialBetaOffset -= 0.01;
  42890. }
  42891. }
  42892. else if (this.keysRight.indexOf(keyCode) !== -1) {
  42893. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  42894. camera.inertialPanningX += 1 / this.panningSensibility;
  42895. }
  42896. else {
  42897. camera.inertialAlphaOffset += 0.01;
  42898. }
  42899. }
  42900. else if (this.keysDown.indexOf(keyCode) !== -1) {
  42901. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  42902. camera.inertialPanningY -= 1 / this.panningSensibility;
  42903. }
  42904. else if (this._altPressed && this.useAltToZoom) {
  42905. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  42906. }
  42907. else {
  42908. camera.inertialBetaOffset += 0.01;
  42909. }
  42910. }
  42911. else if (this.keysReset.indexOf(keyCode) !== -1) {
  42912. camera.restoreState();
  42913. }
  42914. }
  42915. }
  42916. };
  42917. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  42918. return "ArcRotateCameraKeyboardMoveInput";
  42919. };
  42920. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  42921. return "keyboard";
  42922. };
  42923. __decorate([
  42924. BABYLON.serialize()
  42925. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  42926. __decorate([
  42927. BABYLON.serialize()
  42928. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  42929. __decorate([
  42930. BABYLON.serialize()
  42931. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  42932. __decorate([
  42933. BABYLON.serialize()
  42934. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  42935. __decorate([
  42936. BABYLON.serialize()
  42937. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  42938. __decorate([
  42939. BABYLON.serialize()
  42940. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  42941. __decorate([
  42942. BABYLON.serialize()
  42943. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  42944. __decorate([
  42945. BABYLON.serialize()
  42946. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  42947. return ArcRotateCameraKeyboardMoveInput;
  42948. }());
  42949. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  42950. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  42951. })(BABYLON || (BABYLON = {}));
  42952. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  42953. var BABYLON;
  42954. (function (BABYLON) {
  42955. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  42956. function ArcRotateCameraMouseWheelInput() {
  42957. this.wheelPrecision = 3.0;
  42958. /**
  42959. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  42960. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  42961. */
  42962. this.wheelDeltaPercentage = 0;
  42963. }
  42964. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  42965. var _this = this;
  42966. this._wheel = function (p, s) {
  42967. //sanity check - this should be a PointerWheel event.
  42968. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  42969. return;
  42970. var event = p.event;
  42971. var delta = 0;
  42972. if (event.wheelDelta) {
  42973. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  42974. }
  42975. else if (event.detail) {
  42976. delta = -event.detail / _this.wheelPrecision;
  42977. }
  42978. if (delta)
  42979. _this.camera.inertialRadiusOffset += delta;
  42980. if (event.preventDefault) {
  42981. if (!noPreventDefault) {
  42982. event.preventDefault();
  42983. }
  42984. }
  42985. };
  42986. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  42987. };
  42988. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  42989. if (this._observer && element) {
  42990. this.camera.getScene().onPointerObservable.remove(this._observer);
  42991. this._observer = null;
  42992. this._wheel = null;
  42993. }
  42994. };
  42995. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  42996. return "ArcRotateCameraMouseWheelInput";
  42997. };
  42998. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  42999. return "mousewheel";
  43000. };
  43001. __decorate([
  43002. BABYLON.serialize()
  43003. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  43004. __decorate([
  43005. BABYLON.serialize()
  43006. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  43007. return ArcRotateCameraMouseWheelInput;
  43008. }());
  43009. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  43010. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  43011. })(BABYLON || (BABYLON = {}));
  43012. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  43013. var BABYLON;
  43014. (function (BABYLON) {
  43015. var ArcRotateCameraPointersInput = /** @class */ (function () {
  43016. function ArcRotateCameraPointersInput() {
  43017. this.buttons = [0, 1, 2];
  43018. this.angularSensibilityX = 1000.0;
  43019. this.angularSensibilityY = 1000.0;
  43020. this.pinchPrecision = 12.0;
  43021. /**
  43022. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  43023. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  43024. */
  43025. this.pinchDeltaPercentage = 0;
  43026. this.panningSensibility = 1000.0;
  43027. this.multiTouchPanning = true;
  43028. this.multiTouchPanAndZoom = true;
  43029. this._isPanClick = false;
  43030. this.pinchInwards = true;
  43031. }
  43032. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  43033. var _this = this;
  43034. var engine = this.camera.getEngine();
  43035. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  43036. var pointA = null;
  43037. var pointB = null;
  43038. var previousPinchSquaredDistance = 0;
  43039. var initialDistance = 0;
  43040. var twoFingerActivityCount = 0;
  43041. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  43042. this._pointerInput = function (p, s) {
  43043. var evt = p.event;
  43044. var isTouch = p.event.pointerType === "touch";
  43045. if (engine.isInVRExclusivePointerMode) {
  43046. return;
  43047. }
  43048. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43049. return;
  43050. }
  43051. var srcElement = (evt.srcElement || evt.target);
  43052. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43053. try {
  43054. srcElement.setPointerCapture(evt.pointerId);
  43055. }
  43056. catch (e) {
  43057. //Nothing to do with the error. Execution will continue.
  43058. }
  43059. // Manage panning with pan button click
  43060. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  43061. // manage pointers
  43062. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  43063. if (pointA === null) {
  43064. pointA = cacheSoloPointer;
  43065. }
  43066. else if (pointB === null) {
  43067. pointB = cacheSoloPointer;
  43068. }
  43069. if (!noPreventDefault) {
  43070. evt.preventDefault();
  43071. element.focus();
  43072. }
  43073. }
  43074. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  43075. _this.camera.restoreState();
  43076. }
  43077. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43078. try {
  43079. srcElement.releasePointerCapture(evt.pointerId);
  43080. }
  43081. catch (e) {
  43082. //Nothing to do with the error.
  43083. }
  43084. cacheSoloPointer = null;
  43085. previousPinchSquaredDistance = 0;
  43086. previousMultiTouchPanPosition.isPaning = false;
  43087. previousMultiTouchPanPosition.isPinching = false;
  43088. twoFingerActivityCount = 0;
  43089. initialDistance = 0;
  43090. if (!isTouch) {
  43091. pointB = null; // Mouse and pen are mono pointer
  43092. }
  43093. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  43094. //but emptying completly pointers collection is required to fix a bug on iPhone :
  43095. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  43096. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  43097. if (engine.badOS) {
  43098. pointA = pointB = null;
  43099. }
  43100. else {
  43101. //only remove the impacted pointer in case of multitouch allowing on most
  43102. //platforms switching from rotate to zoom and pan seamlessly.
  43103. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  43104. pointA = pointB;
  43105. pointB = null;
  43106. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43107. }
  43108. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  43109. pointB = null;
  43110. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43111. }
  43112. else {
  43113. pointA = pointB = null;
  43114. }
  43115. }
  43116. if (!noPreventDefault) {
  43117. evt.preventDefault();
  43118. }
  43119. }
  43120. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43121. if (!noPreventDefault) {
  43122. evt.preventDefault();
  43123. }
  43124. // One button down
  43125. if (pointA && pointB === null && cacheSoloPointer) {
  43126. if (_this.panningSensibility !== 0 &&
  43127. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  43128. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  43129. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  43130. }
  43131. else {
  43132. var offsetX = evt.clientX - cacheSoloPointer.x;
  43133. var offsetY = evt.clientY - cacheSoloPointer.y;
  43134. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43135. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43136. }
  43137. cacheSoloPointer.x = evt.clientX;
  43138. cacheSoloPointer.y = evt.clientY;
  43139. }
  43140. else if (pointA && pointB) {
  43141. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  43142. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  43143. ed.x = evt.clientX;
  43144. ed.y = evt.clientY;
  43145. var direction = _this.pinchInwards ? 1 : -1;
  43146. var distX = pointA.x - pointB.x;
  43147. var distY = pointA.y - pointB.y;
  43148. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  43149. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  43150. if (previousPinchSquaredDistance === 0) {
  43151. initialDistance = pinchDistance;
  43152. previousPinchSquaredDistance = pinchSquaredDistance;
  43153. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  43154. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  43155. return;
  43156. }
  43157. if (_this.multiTouchPanAndZoom) {
  43158. if (_this.pinchDeltaPercentage) {
  43159. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43160. }
  43161. else {
  43162. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43163. (_this.pinchPrecision *
  43164. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43165. direction);
  43166. }
  43167. if (_this.panningSensibility !== 0) {
  43168. var pointersCenterX = (pointA.x + pointB.x) / 2;
  43169. var pointersCenterY = (pointA.y + pointB.y) / 2;
  43170. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  43171. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  43172. previousMultiTouchPanPosition.x = pointersCenterX;
  43173. previousMultiTouchPanPosition.y = pointersCenterY;
  43174. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  43175. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  43176. }
  43177. }
  43178. else {
  43179. twoFingerActivityCount++;
  43180. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  43181. if (_this.pinchDeltaPercentage) {
  43182. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43183. }
  43184. else {
  43185. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43186. (_this.pinchPrecision *
  43187. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43188. direction);
  43189. }
  43190. previousMultiTouchPanPosition.isPaning = false;
  43191. previousMultiTouchPanPosition.isPinching = true;
  43192. }
  43193. else {
  43194. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  43195. if (!previousMultiTouchPanPosition.isPaning) {
  43196. previousMultiTouchPanPosition.isPaning = true;
  43197. previousMultiTouchPanPosition.isPinching = false;
  43198. previousMultiTouchPanPosition.x = ed.x;
  43199. previousMultiTouchPanPosition.y = ed.y;
  43200. return;
  43201. }
  43202. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  43203. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  43204. }
  43205. }
  43206. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  43207. previousMultiTouchPanPosition.x = ed.x;
  43208. previousMultiTouchPanPosition.y = ed.y;
  43209. }
  43210. }
  43211. previousPinchSquaredDistance = pinchSquaredDistance;
  43212. }
  43213. }
  43214. };
  43215. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  43216. this._onContextMenu = function (evt) {
  43217. evt.preventDefault();
  43218. };
  43219. if (!this.camera._useCtrlForPanning) {
  43220. element.addEventListener("contextmenu", this._onContextMenu, false);
  43221. }
  43222. this._onLostFocus = function () {
  43223. //this._keys = [];
  43224. pointA = pointB = null;
  43225. previousPinchSquaredDistance = 0;
  43226. previousMultiTouchPanPosition.isPaning = false;
  43227. previousMultiTouchPanPosition.isPinching = false;
  43228. twoFingerActivityCount = 0;
  43229. cacheSoloPointer = null;
  43230. initialDistance = 0;
  43231. };
  43232. this._onMouseMove = function (evt) {
  43233. if (!engine.isPointerLock) {
  43234. return;
  43235. }
  43236. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43237. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43238. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43239. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43240. if (!noPreventDefault) {
  43241. evt.preventDefault();
  43242. }
  43243. };
  43244. this._onGestureStart = function (e) {
  43245. if (window.MSGesture === undefined) {
  43246. return;
  43247. }
  43248. if (!_this._MSGestureHandler) {
  43249. _this._MSGestureHandler = new MSGesture();
  43250. _this._MSGestureHandler.target = element;
  43251. }
  43252. _this._MSGestureHandler.addPointer(e.pointerId);
  43253. };
  43254. this._onGesture = function (e) {
  43255. _this.camera.radius *= e.scale;
  43256. if (e.preventDefault) {
  43257. if (!noPreventDefault) {
  43258. e.stopPropagation();
  43259. e.preventDefault();
  43260. }
  43261. }
  43262. };
  43263. element.addEventListener("mousemove", this._onMouseMove, false);
  43264. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  43265. element.addEventListener("MSGestureChange", this._onGesture, false);
  43266. BABYLON.Tools.RegisterTopRootEvents([
  43267. { name: "blur", handler: this._onLostFocus }
  43268. ]);
  43269. };
  43270. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  43271. if (this._onLostFocus) {
  43272. BABYLON.Tools.UnregisterTopRootEvents([
  43273. { name: "blur", handler: this._onLostFocus }
  43274. ]);
  43275. }
  43276. if (element && this._observer) {
  43277. this.camera.getScene().onPointerObservable.remove(this._observer);
  43278. this._observer = null;
  43279. if (this._onContextMenu) {
  43280. element.removeEventListener("contextmenu", this._onContextMenu);
  43281. }
  43282. if (this._onMouseMove) {
  43283. element.removeEventListener("mousemove", this._onMouseMove);
  43284. }
  43285. if (this._onGestureStart) {
  43286. element.removeEventListener("MSPointerDown", this._onGestureStart);
  43287. }
  43288. if (this._onGesture) {
  43289. element.removeEventListener("MSGestureChange", this._onGesture);
  43290. }
  43291. this._isPanClick = false;
  43292. this.pinchInwards = true;
  43293. this._onMouseMove = null;
  43294. this._onGestureStart = null;
  43295. this._onGesture = null;
  43296. this._MSGestureHandler = null;
  43297. this._onLostFocus = null;
  43298. this._onContextMenu = null;
  43299. }
  43300. };
  43301. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  43302. return "ArcRotateCameraPointersInput";
  43303. };
  43304. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  43305. return "pointers";
  43306. };
  43307. __decorate([
  43308. BABYLON.serialize()
  43309. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  43310. __decorate([
  43311. BABYLON.serialize()
  43312. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  43313. __decorate([
  43314. BABYLON.serialize()
  43315. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  43316. __decorate([
  43317. BABYLON.serialize()
  43318. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  43319. __decorate([
  43320. BABYLON.serialize()
  43321. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  43322. __decorate([
  43323. BABYLON.serialize()
  43324. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  43325. __decorate([
  43326. BABYLON.serialize()
  43327. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  43328. __decorate([
  43329. BABYLON.serialize()
  43330. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  43331. return ArcRotateCameraPointersInput;
  43332. }());
  43333. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  43334. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  43335. })(BABYLON || (BABYLON = {}));
  43336. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  43337. var BABYLON;
  43338. (function (BABYLON) {
  43339. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  43340. __extends(ArcRotateCameraInputsManager, _super);
  43341. function ArcRotateCameraInputsManager(camera) {
  43342. return _super.call(this, camera) || this;
  43343. }
  43344. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  43345. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  43346. return this;
  43347. };
  43348. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  43349. this.add(new BABYLON.ArcRotateCameraPointersInput());
  43350. return this;
  43351. };
  43352. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  43353. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  43354. return this;
  43355. };
  43356. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  43357. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  43358. return this;
  43359. };
  43360. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  43361. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  43362. return this;
  43363. };
  43364. return ArcRotateCameraInputsManager;
  43365. }(BABYLON.CameraInputsManager));
  43366. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  43367. })(BABYLON || (BABYLON = {}));
  43368. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  43369. var BABYLON;
  43370. (function (BABYLON) {
  43371. var ArcRotateCamera = /** @class */ (function (_super) {
  43372. __extends(ArcRotateCamera, _super);
  43373. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  43374. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  43375. _this.inertialAlphaOffset = 0;
  43376. _this.inertialBetaOffset = 0;
  43377. _this.inertialRadiusOffset = 0;
  43378. _this.lowerAlphaLimit = null;
  43379. _this.upperAlphaLimit = null;
  43380. _this.lowerBetaLimit = 0.01;
  43381. _this.upperBetaLimit = Math.PI;
  43382. _this.lowerRadiusLimit = null;
  43383. _this.upperRadiusLimit = null;
  43384. _this.inertialPanningX = 0;
  43385. _this.inertialPanningY = 0;
  43386. _this.pinchToPanMaxDistance = 20;
  43387. _this.panningDistanceLimit = null;
  43388. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  43389. _this.panningInertia = 0.9;
  43390. //-- end properties for backward compatibility for inputs
  43391. _this.zoomOnFactor = 1;
  43392. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  43393. _this.allowUpsideDown = true;
  43394. _this._viewMatrix = new BABYLON.Matrix();
  43395. // Panning
  43396. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  43397. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  43398. _this.checkCollisions = false;
  43399. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  43400. _this._previousPosition = BABYLON.Vector3.Zero();
  43401. _this._collisionVelocity = BABYLON.Vector3.Zero();
  43402. _this._newPosition = BABYLON.Vector3.Zero();
  43403. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43404. if (collidedMesh === void 0) { collidedMesh = null; }
  43405. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  43406. newPosition.multiplyInPlace(_this._collider._radius);
  43407. }
  43408. if (!collidedMesh) {
  43409. _this._previousPosition.copyFrom(_this.position);
  43410. }
  43411. else {
  43412. _this.setPosition(newPosition);
  43413. if (_this.onCollide) {
  43414. _this.onCollide(collidedMesh);
  43415. }
  43416. }
  43417. // Recompute because of constraints
  43418. var cosa = Math.cos(_this.alpha);
  43419. var sina = Math.sin(_this.alpha);
  43420. var cosb = Math.cos(_this.beta);
  43421. var sinb = Math.sin(_this.beta);
  43422. if (sinb === 0) {
  43423. sinb = 0.0001;
  43424. }
  43425. var target = _this._getTargetPosition();
  43426. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  43427. _this.position.copyFrom(_this._newPosition);
  43428. var up = _this.upVector;
  43429. if (_this.allowUpsideDown && _this.beta < 0) {
  43430. up = up.clone();
  43431. up = up.negate();
  43432. }
  43433. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  43434. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  43435. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  43436. _this._collisionTriggered = false;
  43437. };
  43438. _this._target = BABYLON.Vector3.Zero();
  43439. if (target) {
  43440. _this.setTarget(target);
  43441. }
  43442. _this.alpha = alpha;
  43443. _this.beta = beta;
  43444. _this.radius = radius;
  43445. _this.getViewMatrix();
  43446. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  43447. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  43448. return _this;
  43449. }
  43450. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  43451. get: function () {
  43452. return this._target;
  43453. },
  43454. set: function (value) {
  43455. this.setTarget(value);
  43456. },
  43457. enumerable: true,
  43458. configurable: true
  43459. });
  43460. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  43461. //-- begin properties for backward compatibility for inputs
  43462. get: function () {
  43463. var pointers = this.inputs.attached["pointers"];
  43464. if (pointers)
  43465. return pointers.angularSensibilityX;
  43466. return 0;
  43467. },
  43468. set: function (value) {
  43469. var pointers = this.inputs.attached["pointers"];
  43470. if (pointers) {
  43471. pointers.angularSensibilityX = value;
  43472. }
  43473. },
  43474. enumerable: true,
  43475. configurable: true
  43476. });
  43477. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  43478. get: function () {
  43479. var pointers = this.inputs.attached["pointers"];
  43480. if (pointers)
  43481. return pointers.angularSensibilityY;
  43482. return 0;
  43483. },
  43484. set: function (value) {
  43485. var pointers = this.inputs.attached["pointers"];
  43486. if (pointers) {
  43487. pointers.angularSensibilityY = value;
  43488. }
  43489. },
  43490. enumerable: true,
  43491. configurable: true
  43492. });
  43493. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  43494. get: function () {
  43495. var pointers = this.inputs.attached["pointers"];
  43496. if (pointers)
  43497. return pointers.pinchPrecision;
  43498. return 0;
  43499. },
  43500. set: function (value) {
  43501. var pointers = this.inputs.attached["pointers"];
  43502. if (pointers) {
  43503. pointers.pinchPrecision = value;
  43504. }
  43505. },
  43506. enumerable: true,
  43507. configurable: true
  43508. });
  43509. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  43510. get: function () {
  43511. var pointers = this.inputs.attached["pointers"];
  43512. if (pointers)
  43513. return pointers.pinchDeltaPercentage;
  43514. return 0;
  43515. },
  43516. set: function (value) {
  43517. var pointers = this.inputs.attached["pointers"];
  43518. if (pointers) {
  43519. pointers.pinchDeltaPercentage = value;
  43520. }
  43521. },
  43522. enumerable: true,
  43523. configurable: true
  43524. });
  43525. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  43526. get: function () {
  43527. var pointers = this.inputs.attached["pointers"];
  43528. if (pointers)
  43529. return pointers.panningSensibility;
  43530. return 0;
  43531. },
  43532. set: function (value) {
  43533. var pointers = this.inputs.attached["pointers"];
  43534. if (pointers) {
  43535. pointers.panningSensibility = value;
  43536. }
  43537. },
  43538. enumerable: true,
  43539. configurable: true
  43540. });
  43541. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  43542. get: function () {
  43543. var keyboard = this.inputs.attached["keyboard"];
  43544. if (keyboard)
  43545. return keyboard.keysUp;
  43546. return [];
  43547. },
  43548. set: function (value) {
  43549. var keyboard = this.inputs.attached["keyboard"];
  43550. if (keyboard)
  43551. keyboard.keysUp = value;
  43552. },
  43553. enumerable: true,
  43554. configurable: true
  43555. });
  43556. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  43557. get: function () {
  43558. var keyboard = this.inputs.attached["keyboard"];
  43559. if (keyboard)
  43560. return keyboard.keysDown;
  43561. return [];
  43562. },
  43563. set: function (value) {
  43564. var keyboard = this.inputs.attached["keyboard"];
  43565. if (keyboard)
  43566. keyboard.keysDown = value;
  43567. },
  43568. enumerable: true,
  43569. configurable: true
  43570. });
  43571. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  43572. get: function () {
  43573. var keyboard = this.inputs.attached["keyboard"];
  43574. if (keyboard)
  43575. return keyboard.keysLeft;
  43576. return [];
  43577. },
  43578. set: function (value) {
  43579. var keyboard = this.inputs.attached["keyboard"];
  43580. if (keyboard)
  43581. keyboard.keysLeft = value;
  43582. },
  43583. enumerable: true,
  43584. configurable: true
  43585. });
  43586. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  43587. get: function () {
  43588. var keyboard = this.inputs.attached["keyboard"];
  43589. if (keyboard)
  43590. return keyboard.keysRight;
  43591. return [];
  43592. },
  43593. set: function (value) {
  43594. var keyboard = this.inputs.attached["keyboard"];
  43595. if (keyboard)
  43596. keyboard.keysRight = value;
  43597. },
  43598. enumerable: true,
  43599. configurable: true
  43600. });
  43601. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  43602. get: function () {
  43603. var mousewheel = this.inputs.attached["mousewheel"];
  43604. if (mousewheel)
  43605. return mousewheel.wheelPrecision;
  43606. return 0;
  43607. },
  43608. set: function (value) {
  43609. var mousewheel = this.inputs.attached["mousewheel"];
  43610. if (mousewheel)
  43611. mousewheel.wheelPrecision = value;
  43612. },
  43613. enumerable: true,
  43614. configurable: true
  43615. });
  43616. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  43617. get: function () {
  43618. var mousewheel = this.inputs.attached["mousewheel"];
  43619. if (mousewheel)
  43620. return mousewheel.wheelDeltaPercentage;
  43621. return 0;
  43622. },
  43623. set: function (value) {
  43624. var mousewheel = this.inputs.attached["mousewheel"];
  43625. if (mousewheel)
  43626. mousewheel.wheelDeltaPercentage = value;
  43627. },
  43628. enumerable: true,
  43629. configurable: true
  43630. });
  43631. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  43632. get: function () {
  43633. return this._bouncingBehavior;
  43634. },
  43635. enumerable: true,
  43636. configurable: true
  43637. });
  43638. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  43639. get: function () {
  43640. return this._bouncingBehavior != null;
  43641. },
  43642. set: function (value) {
  43643. if (value === this.useBouncingBehavior) {
  43644. return;
  43645. }
  43646. if (value) {
  43647. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  43648. this.addBehavior(this._bouncingBehavior);
  43649. }
  43650. else if (this._bouncingBehavior) {
  43651. this.removeBehavior(this._bouncingBehavior);
  43652. this._bouncingBehavior = null;
  43653. }
  43654. },
  43655. enumerable: true,
  43656. configurable: true
  43657. });
  43658. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  43659. get: function () {
  43660. return this._framingBehavior;
  43661. },
  43662. enumerable: true,
  43663. configurable: true
  43664. });
  43665. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  43666. get: function () {
  43667. return this._framingBehavior != null;
  43668. },
  43669. set: function (value) {
  43670. if (value === this.useFramingBehavior) {
  43671. return;
  43672. }
  43673. if (value) {
  43674. this._framingBehavior = new BABYLON.FramingBehavior();
  43675. this.addBehavior(this._framingBehavior);
  43676. }
  43677. else if (this._framingBehavior) {
  43678. this.removeBehavior(this._framingBehavior);
  43679. this._framingBehavior = null;
  43680. }
  43681. },
  43682. enumerable: true,
  43683. configurable: true
  43684. });
  43685. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  43686. get: function () {
  43687. return this._autoRotationBehavior;
  43688. },
  43689. enumerable: true,
  43690. configurable: true
  43691. });
  43692. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  43693. get: function () {
  43694. return this._autoRotationBehavior != null;
  43695. },
  43696. set: function (value) {
  43697. if (value === this.useAutoRotationBehavior) {
  43698. return;
  43699. }
  43700. if (value) {
  43701. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  43702. this.addBehavior(this._autoRotationBehavior);
  43703. }
  43704. else if (this._autoRotationBehavior) {
  43705. this.removeBehavior(this._autoRotationBehavior);
  43706. this._autoRotationBehavior = null;
  43707. }
  43708. },
  43709. enumerable: true,
  43710. configurable: true
  43711. });
  43712. // Cache
  43713. ArcRotateCamera.prototype._initCache = function () {
  43714. _super.prototype._initCache.call(this);
  43715. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43716. this._cache.alpha = undefined;
  43717. this._cache.beta = undefined;
  43718. this._cache.radius = undefined;
  43719. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  43720. };
  43721. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  43722. if (!ignoreParentClass) {
  43723. _super.prototype._updateCache.call(this);
  43724. }
  43725. this._cache._target.copyFrom(this._getTargetPosition());
  43726. this._cache.alpha = this.alpha;
  43727. this._cache.beta = this.beta;
  43728. this._cache.radius = this.radius;
  43729. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  43730. };
  43731. ArcRotateCamera.prototype._getTargetPosition = function () {
  43732. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  43733. var pos = this._targetHost.getAbsolutePosition();
  43734. if (this._targetBoundingCenter) {
  43735. pos.addToRef(this._targetBoundingCenter, this._target);
  43736. }
  43737. else {
  43738. this._target.copyFrom(pos);
  43739. }
  43740. }
  43741. var lockedTargetPosition = this._getLockedTargetPosition();
  43742. if (lockedTargetPosition) {
  43743. return lockedTargetPosition;
  43744. }
  43745. return this._target;
  43746. };
  43747. ArcRotateCamera.prototype.storeState = function () {
  43748. this._storedAlpha = this.alpha;
  43749. this._storedBeta = this.beta;
  43750. this._storedRadius = this.radius;
  43751. this._storedTarget = this._getTargetPosition().clone();
  43752. return _super.prototype.storeState.call(this);
  43753. };
  43754. /**
  43755. * Restored camera state. You must call storeState() first
  43756. */
  43757. ArcRotateCamera.prototype._restoreStateValues = function () {
  43758. if (!_super.prototype._restoreStateValues.call(this)) {
  43759. return false;
  43760. }
  43761. this.alpha = this._storedAlpha;
  43762. this.beta = this._storedBeta;
  43763. this.radius = this._storedRadius;
  43764. this.setTarget(this._storedTarget.clone());
  43765. this.inertialAlphaOffset = 0;
  43766. this.inertialBetaOffset = 0;
  43767. this.inertialRadiusOffset = 0;
  43768. this.inertialPanningX = 0;
  43769. this.inertialPanningY = 0;
  43770. return true;
  43771. };
  43772. // Synchronized
  43773. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  43774. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  43775. return false;
  43776. return this._cache._target.equals(this._getTargetPosition())
  43777. && this._cache.alpha === this.alpha
  43778. && this._cache.beta === this.beta
  43779. && this._cache.radius === this.radius
  43780. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  43781. };
  43782. // Methods
  43783. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  43784. var _this = this;
  43785. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  43786. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  43787. this._useCtrlForPanning = useCtrlForPanning;
  43788. this._panningMouseButton = panningMouseButton;
  43789. this.inputs.attachElement(element, noPreventDefault);
  43790. this._reset = function () {
  43791. _this.inertialAlphaOffset = 0;
  43792. _this.inertialBetaOffset = 0;
  43793. _this.inertialRadiusOffset = 0;
  43794. _this.inertialPanningX = 0;
  43795. _this.inertialPanningY = 0;
  43796. };
  43797. };
  43798. ArcRotateCamera.prototype.detachControl = function (element) {
  43799. this.inputs.detachElement(element);
  43800. if (this._reset) {
  43801. this._reset();
  43802. }
  43803. };
  43804. ArcRotateCamera.prototype._checkInputs = function () {
  43805. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  43806. if (this._collisionTriggered) {
  43807. return;
  43808. }
  43809. this.inputs.checkInputs();
  43810. // Inertia
  43811. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  43812. if (this.getScene().useRightHandedSystem) {
  43813. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  43814. }
  43815. else {
  43816. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  43817. }
  43818. this.beta += this.inertialBetaOffset;
  43819. this.radius -= this.inertialRadiusOffset;
  43820. this.inertialAlphaOffset *= this.inertia;
  43821. this.inertialBetaOffset *= this.inertia;
  43822. this.inertialRadiusOffset *= this.inertia;
  43823. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  43824. this.inertialAlphaOffset = 0;
  43825. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  43826. this.inertialBetaOffset = 0;
  43827. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  43828. this.inertialRadiusOffset = 0;
  43829. }
  43830. // Panning inertia
  43831. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  43832. if (!this._localDirection) {
  43833. this._localDirection = BABYLON.Vector3.Zero();
  43834. this._transformedDirection = BABYLON.Vector3.Zero();
  43835. }
  43836. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  43837. this._localDirection.multiplyInPlace(this.panningAxis);
  43838. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  43839. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  43840. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  43841. if (!this.panningAxis.y) {
  43842. this._transformedDirection.y = 0;
  43843. }
  43844. if (!this._targetHost) {
  43845. if (this.panningDistanceLimit) {
  43846. this._transformedDirection.addInPlace(this._target);
  43847. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  43848. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  43849. this._target.copyFrom(this._transformedDirection);
  43850. }
  43851. }
  43852. else {
  43853. this._target.addInPlace(this._transformedDirection);
  43854. }
  43855. }
  43856. this.inertialPanningX *= this.panningInertia;
  43857. this.inertialPanningY *= this.panningInertia;
  43858. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  43859. this.inertialPanningX = 0;
  43860. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  43861. this.inertialPanningY = 0;
  43862. }
  43863. // Limits
  43864. this._checkLimits();
  43865. _super.prototype._checkInputs.call(this);
  43866. };
  43867. ArcRotateCamera.prototype._checkLimits = function () {
  43868. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  43869. if (this.allowUpsideDown && this.beta > Math.PI) {
  43870. this.beta = this.beta - (2 * Math.PI);
  43871. }
  43872. }
  43873. else {
  43874. if (this.beta < this.lowerBetaLimit) {
  43875. this.beta = this.lowerBetaLimit;
  43876. }
  43877. }
  43878. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  43879. if (this.allowUpsideDown && this.beta < -Math.PI) {
  43880. this.beta = this.beta + (2 * Math.PI);
  43881. }
  43882. }
  43883. else {
  43884. if (this.beta > this.upperBetaLimit) {
  43885. this.beta = this.upperBetaLimit;
  43886. }
  43887. }
  43888. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  43889. this.alpha = this.lowerAlphaLimit;
  43890. }
  43891. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  43892. this.alpha = this.upperAlphaLimit;
  43893. }
  43894. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  43895. this.radius = this.lowerRadiusLimit;
  43896. }
  43897. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  43898. this.radius = this.upperRadiusLimit;
  43899. }
  43900. };
  43901. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  43902. var radiusv3 = this.position.subtract(this._getTargetPosition());
  43903. this.radius = radiusv3.length();
  43904. if (this.radius === 0) {
  43905. this.radius = 0.0001; // Just to avoid division by zero
  43906. }
  43907. // Alpha
  43908. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  43909. if (radiusv3.z < 0) {
  43910. this.alpha = 2 * Math.PI - this.alpha;
  43911. }
  43912. // Beta
  43913. this.beta = Math.acos(radiusv3.y / this.radius);
  43914. this._checkLimits();
  43915. };
  43916. ArcRotateCamera.prototype.setPosition = function (position) {
  43917. if (this.position.equals(position)) {
  43918. return;
  43919. }
  43920. this.position.copyFrom(position);
  43921. this.rebuildAnglesAndRadius();
  43922. };
  43923. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  43924. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  43925. if (allowSamePosition === void 0) { allowSamePosition = false; }
  43926. if (target.getBoundingInfo) {
  43927. if (toBoundingCenter) {
  43928. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  43929. }
  43930. else {
  43931. this._targetBoundingCenter = null;
  43932. }
  43933. this._targetHost = target;
  43934. this._target = this._getTargetPosition();
  43935. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  43936. }
  43937. else {
  43938. var newTarget = target;
  43939. var currentTarget = this._getTargetPosition();
  43940. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  43941. return;
  43942. }
  43943. this._targetHost = null;
  43944. this._target = newTarget;
  43945. this._targetBoundingCenter = null;
  43946. this.onMeshTargetChangedObservable.notifyObservers(null);
  43947. }
  43948. this.rebuildAnglesAndRadius();
  43949. };
  43950. ArcRotateCamera.prototype._getViewMatrix = function () {
  43951. // Compute
  43952. var cosa = Math.cos(this.alpha);
  43953. var sina = Math.sin(this.alpha);
  43954. var cosb = Math.cos(this.beta);
  43955. var sinb = Math.sin(this.beta);
  43956. if (sinb === 0) {
  43957. sinb = 0.0001;
  43958. }
  43959. var target = this._getTargetPosition();
  43960. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  43961. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  43962. if (!this._collider) {
  43963. this._collider = new BABYLON.Collider();
  43964. }
  43965. this._collider._radius = this.collisionRadius;
  43966. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  43967. this._collisionTriggered = true;
  43968. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43969. }
  43970. else {
  43971. this.position.copyFrom(this._newPosition);
  43972. var up = this.upVector;
  43973. if (this.allowUpsideDown && sinb < 0) {
  43974. up = up.clone();
  43975. up = up.negate();
  43976. }
  43977. if (this.getScene().useRightHandedSystem) {
  43978. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  43979. }
  43980. else {
  43981. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  43982. }
  43983. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  43984. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  43985. }
  43986. this._currentTarget = target;
  43987. return this._viewMatrix;
  43988. };
  43989. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  43990. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  43991. meshes = meshes || this.getScene().meshes;
  43992. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  43993. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  43994. this.radius = distance * this.zoomOnFactor;
  43995. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  43996. };
  43997. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  43998. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  43999. var meshesOrMinMaxVector;
  44000. var distance;
  44001. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  44002. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  44003. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  44004. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  44005. }
  44006. else {
  44007. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  44008. meshesOrMinMaxVector = minMaxVectorAndDistance;
  44009. distance = minMaxVectorAndDistance.distance;
  44010. }
  44011. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  44012. if (!doNotUpdateMaxZ) {
  44013. this.maxZ = distance * 2;
  44014. }
  44015. };
  44016. /**
  44017. * @override
  44018. * Override Camera.createRigCamera
  44019. */
  44020. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  44021. var alphaShift = 0;
  44022. switch (this.cameraRigMode) {
  44023. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44024. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44025. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44026. case BABYLON.Camera.RIG_MODE_VR:
  44027. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  44028. break;
  44029. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44030. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  44031. break;
  44032. }
  44033. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  44034. rigCam._cameraRigParams = {};
  44035. return rigCam;
  44036. };
  44037. /**
  44038. * @override
  44039. * Override Camera._updateRigCameras
  44040. */
  44041. ArcRotateCamera.prototype._updateRigCameras = function () {
  44042. var camLeft = this._rigCameras[0];
  44043. var camRight = this._rigCameras[1];
  44044. camLeft.beta = camRight.beta = this.beta;
  44045. camLeft.radius = camRight.radius = this.radius;
  44046. switch (this.cameraRigMode) {
  44047. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44048. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44049. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44050. case BABYLON.Camera.RIG_MODE_VR:
  44051. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44052. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44053. break;
  44054. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44055. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44056. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44057. break;
  44058. }
  44059. _super.prototype._updateRigCameras.call(this);
  44060. };
  44061. ArcRotateCamera.prototype.dispose = function () {
  44062. this.inputs.clear();
  44063. _super.prototype.dispose.call(this);
  44064. };
  44065. ArcRotateCamera.prototype.getClassName = function () {
  44066. return "ArcRotateCamera";
  44067. };
  44068. __decorate([
  44069. BABYLON.serialize()
  44070. ], ArcRotateCamera.prototype, "alpha", void 0);
  44071. __decorate([
  44072. BABYLON.serialize()
  44073. ], ArcRotateCamera.prototype, "beta", void 0);
  44074. __decorate([
  44075. BABYLON.serialize()
  44076. ], ArcRotateCamera.prototype, "radius", void 0);
  44077. __decorate([
  44078. BABYLON.serializeAsVector3("target")
  44079. ], ArcRotateCamera.prototype, "_target", void 0);
  44080. __decorate([
  44081. BABYLON.serialize()
  44082. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  44083. __decorate([
  44084. BABYLON.serialize()
  44085. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  44086. __decorate([
  44087. BABYLON.serialize()
  44088. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  44089. __decorate([
  44090. BABYLON.serialize()
  44091. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  44092. __decorate([
  44093. BABYLON.serialize()
  44094. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  44095. __decorate([
  44096. BABYLON.serialize()
  44097. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  44098. __decorate([
  44099. BABYLON.serialize()
  44100. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  44101. __decorate([
  44102. BABYLON.serialize()
  44103. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  44104. __decorate([
  44105. BABYLON.serialize()
  44106. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  44107. __decorate([
  44108. BABYLON.serialize()
  44109. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  44110. __decorate([
  44111. BABYLON.serialize()
  44112. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  44113. __decorate([
  44114. BABYLON.serialize()
  44115. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  44116. __decorate([
  44117. BABYLON.serialize()
  44118. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  44119. __decorate([
  44120. BABYLON.serializeAsVector3()
  44121. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  44122. __decorate([
  44123. BABYLON.serialize()
  44124. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  44125. __decorate([
  44126. BABYLON.serialize()
  44127. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  44128. __decorate([
  44129. BABYLON.serialize()
  44130. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  44131. return ArcRotateCamera;
  44132. }(BABYLON.TargetCamera));
  44133. BABYLON.ArcRotateCamera = ArcRotateCamera;
  44134. })(BABYLON || (BABYLON = {}));
  44135. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  44136. var BABYLON;
  44137. (function (BABYLON) {
  44138. /**
  44139. * The HemisphericLight simulates the ambient environment light,
  44140. * so the passed direction is the light reflection direction, not the incoming direction.
  44141. */
  44142. var HemisphericLight = /** @class */ (function (_super) {
  44143. __extends(HemisphericLight, _super);
  44144. /**
  44145. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  44146. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  44147. * The HemisphericLight can't cast shadows.
  44148. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44149. * @param name The friendly name of the light
  44150. * @param direction The direction of the light reflection
  44151. * @param scene The scene the light belongs to
  44152. */
  44153. function HemisphericLight(name, direction, scene) {
  44154. var _this = _super.call(this, name, scene) || this;
  44155. /**
  44156. * The groundColor is the light in the opposite direction to the one specified during creation.
  44157. * 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.
  44158. */
  44159. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  44160. _this.direction = direction || BABYLON.Vector3.Up();
  44161. return _this;
  44162. }
  44163. HemisphericLight.prototype._buildUniformLayout = function () {
  44164. this._uniformBuffer.addUniform("vLightData", 4);
  44165. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  44166. this._uniformBuffer.addUniform("vLightSpecular", 3);
  44167. this._uniformBuffer.addUniform("vLightGround", 3);
  44168. this._uniformBuffer.addUniform("shadowsInfo", 3);
  44169. this._uniformBuffer.addUniform("depthValues", 2);
  44170. this._uniformBuffer.create();
  44171. };
  44172. /**
  44173. * Returns the string "HemisphericLight".
  44174. * @return The class name
  44175. */
  44176. HemisphericLight.prototype.getClassName = function () {
  44177. return "HemisphericLight";
  44178. };
  44179. /**
  44180. * Sets the HemisphericLight direction towards the passed target (Vector3).
  44181. * Returns the updated direction.
  44182. * @param target The target the direction should point to
  44183. * @return The computed direction
  44184. */
  44185. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  44186. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  44187. return this.direction;
  44188. };
  44189. /**
  44190. * Returns the shadow generator associated to the light.
  44191. * @returns Always null for hemispheric lights because it does not support shadows.
  44192. */
  44193. HemisphericLight.prototype.getShadowGenerator = function () {
  44194. return null;
  44195. };
  44196. /**
  44197. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  44198. * @param effect The effect to update
  44199. * @param lightIndex The index of the light in the effect to update
  44200. * @returns The hemispheric light
  44201. */
  44202. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  44203. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  44204. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  44205. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  44206. return this;
  44207. };
  44208. /**
  44209. * @ignore internal use only.
  44210. */
  44211. HemisphericLight.prototype._getWorldMatrix = function () {
  44212. if (!this._worldMatrix) {
  44213. this._worldMatrix = BABYLON.Matrix.Identity();
  44214. }
  44215. return this._worldMatrix;
  44216. };
  44217. /**
  44218. * Returns the integer 3.
  44219. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44220. */
  44221. HemisphericLight.prototype.getTypeID = function () {
  44222. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  44223. };
  44224. __decorate([
  44225. BABYLON.serializeAsColor3()
  44226. ], HemisphericLight.prototype, "groundColor", void 0);
  44227. __decorate([
  44228. BABYLON.serializeAsVector3()
  44229. ], HemisphericLight.prototype, "direction", void 0);
  44230. return HemisphericLight;
  44231. }(BABYLON.Light));
  44232. BABYLON.HemisphericLight = HemisphericLight;
  44233. })(BABYLON || (BABYLON = {}));
  44234. //# sourceMappingURL=babylon.hemisphericLight.js.map
  44235. var BABYLON;
  44236. (function (BABYLON) {
  44237. /**
  44238. * Base implementation of @see IShadowLight
  44239. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  44240. */
  44241. var ShadowLight = /** @class */ (function (_super) {
  44242. __extends(ShadowLight, _super);
  44243. function ShadowLight() {
  44244. var _this = _super !== null && _super.apply(this, arguments) || this;
  44245. _this._needProjectionMatrixCompute = true;
  44246. return _this;
  44247. }
  44248. ShadowLight.prototype._setPosition = function (value) {
  44249. this._position = value;
  44250. };
  44251. Object.defineProperty(ShadowLight.prototype, "position", {
  44252. /**
  44253. * Sets the position the shadow will be casted from. Also use as the light position for both
  44254. * point and spot lights.
  44255. */
  44256. get: function () {
  44257. return this._position;
  44258. },
  44259. /**
  44260. * Sets the position the shadow will be casted from. Also use as the light position for both
  44261. * point and spot lights.
  44262. */
  44263. set: function (value) {
  44264. this._setPosition(value);
  44265. },
  44266. enumerable: true,
  44267. configurable: true
  44268. });
  44269. ShadowLight.prototype._setDirection = function (value) {
  44270. this._direction = value;
  44271. };
  44272. Object.defineProperty(ShadowLight.prototype, "direction", {
  44273. /**
  44274. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  44275. * Also use as the light direction on spot and directional lights.
  44276. */
  44277. get: function () {
  44278. return this._direction;
  44279. },
  44280. /**
  44281. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  44282. * Also use as the light direction on spot and directional lights.
  44283. */
  44284. set: function (value) {
  44285. this._setDirection(value);
  44286. },
  44287. enumerable: true,
  44288. configurable: true
  44289. });
  44290. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  44291. /**
  44292. * Gets the shadow projection clipping minimum z value.
  44293. */
  44294. get: function () {
  44295. return this._shadowMinZ;
  44296. },
  44297. /**
  44298. * Sets the shadow projection clipping minimum z value.
  44299. */
  44300. set: function (value) {
  44301. this._shadowMinZ = value;
  44302. this.forceProjectionMatrixCompute();
  44303. },
  44304. enumerable: true,
  44305. configurable: true
  44306. });
  44307. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  44308. /**
  44309. * Sets the shadow projection clipping maximum z value.
  44310. */
  44311. get: function () {
  44312. return this._shadowMaxZ;
  44313. },
  44314. /**
  44315. * Gets the shadow projection clipping maximum z value.
  44316. */
  44317. set: function (value) {
  44318. this._shadowMaxZ = value;
  44319. this.forceProjectionMatrixCompute();
  44320. },
  44321. enumerable: true,
  44322. configurable: true
  44323. });
  44324. /**
  44325. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  44326. * @returns true if the information has been computed, false if it does not need to (no parenting)
  44327. */
  44328. ShadowLight.prototype.computeTransformedInformation = function () {
  44329. if (this.parent && this.parent.getWorldMatrix) {
  44330. if (!this.transformedPosition) {
  44331. this.transformedPosition = BABYLON.Vector3.Zero();
  44332. }
  44333. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  44334. // In case the direction is present.
  44335. if (this.direction) {
  44336. if (!this.transformedDirection) {
  44337. this.transformedDirection = BABYLON.Vector3.Zero();
  44338. }
  44339. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  44340. }
  44341. return true;
  44342. }
  44343. return false;
  44344. };
  44345. /**
  44346. * Return the depth scale used for the shadow map.
  44347. * @returns the depth scale.
  44348. */
  44349. ShadowLight.prototype.getDepthScale = function () {
  44350. return 50.0;
  44351. };
  44352. /**
  44353. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  44354. * @param faceIndex The index of the face we are computed the direction to generate shadow
  44355. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  44356. */
  44357. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  44358. return this.transformedDirection ? this.transformedDirection : this.direction;
  44359. };
  44360. /**
  44361. * Returns the ShadowLight absolute position in the World.
  44362. * @returns the position vector in world space
  44363. */
  44364. ShadowLight.prototype.getAbsolutePosition = function () {
  44365. return this.transformedPosition ? this.transformedPosition : this.position;
  44366. };
  44367. /**
  44368. * Sets the ShadowLight direction toward the passed target.
  44369. * @param target The point tot target in local space
  44370. * @returns the updated ShadowLight direction
  44371. */
  44372. ShadowLight.prototype.setDirectionToTarget = function (target) {
  44373. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  44374. return this.direction;
  44375. };
  44376. /**
  44377. * Returns the light rotation in euler definition.
  44378. * @returns the x y z rotation in local space.
  44379. */
  44380. ShadowLight.prototype.getRotation = function () {
  44381. this.direction.normalize();
  44382. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  44383. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  44384. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  44385. };
  44386. /**
  44387. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  44388. * @returns true if a cube texture needs to be use
  44389. */
  44390. ShadowLight.prototype.needCube = function () {
  44391. return false;
  44392. };
  44393. /**
  44394. * Detects if the projection matrix requires to be recomputed this frame.
  44395. * @returns true if it requires to be recomputed otherwise, false.
  44396. */
  44397. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  44398. return this._needProjectionMatrixCompute;
  44399. };
  44400. /**
  44401. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  44402. */
  44403. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  44404. this._needProjectionMatrixCompute = true;
  44405. };
  44406. /**
  44407. * Get the world matrix of the sahdow lights.
  44408. * @ignore Internal Use Only
  44409. */
  44410. ShadowLight.prototype._getWorldMatrix = function () {
  44411. if (!this._worldMatrix) {
  44412. this._worldMatrix = BABYLON.Matrix.Identity();
  44413. }
  44414. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  44415. return this._worldMatrix;
  44416. };
  44417. /**
  44418. * Gets the minZ used for shadow according to both the scene and the light.
  44419. * @param activeCamera The camera we are returning the min for
  44420. * @returns the depth min z
  44421. */
  44422. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  44423. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  44424. };
  44425. /**
  44426. * Gets the maxZ used for shadow according to both the scene and the light.
  44427. * @param activeCamera The camera we are returning the max for
  44428. * @returns the depth max z
  44429. */
  44430. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  44431. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  44432. };
  44433. /**
  44434. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  44435. * @param matrix The materix to updated with the projection information
  44436. * @param viewMatrix The transform matrix of the light
  44437. * @param renderList The list of mesh to render in the map
  44438. * @returns The current light
  44439. */
  44440. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44441. if (this.customProjectionMatrixBuilder) {
  44442. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  44443. }
  44444. else {
  44445. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  44446. }
  44447. return this;
  44448. };
  44449. __decorate([
  44450. BABYLON.serializeAsVector3()
  44451. ], ShadowLight.prototype, "position", null);
  44452. __decorate([
  44453. BABYLON.serializeAsVector3()
  44454. ], ShadowLight.prototype, "direction", null);
  44455. __decorate([
  44456. BABYLON.serialize()
  44457. ], ShadowLight.prototype, "shadowMinZ", null);
  44458. __decorate([
  44459. BABYLON.serialize()
  44460. ], ShadowLight.prototype, "shadowMaxZ", null);
  44461. return ShadowLight;
  44462. }(BABYLON.Light));
  44463. BABYLON.ShadowLight = ShadowLight;
  44464. })(BABYLON || (BABYLON = {}));
  44465. //# sourceMappingURL=babylon.shadowLight.js.map
  44466. var BABYLON;
  44467. (function (BABYLON) {
  44468. /**
  44469. * A point light is a light defined by an unique point in world space.
  44470. * The light is emitted in every direction from this point.
  44471. * A good example of a point light is a standard light bulb.
  44472. * Documentation: https://doc.babylonjs.com/babylon101/lights
  44473. */
  44474. var PointLight = /** @class */ (function (_super) {
  44475. __extends(PointLight, _super);
  44476. /**
  44477. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  44478. * A PointLight emits the light in every direction.
  44479. * It can cast shadows.
  44480. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  44481. * ```javascript
  44482. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  44483. * ```
  44484. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44485. * @param name The light friendly name
  44486. * @param position The position of the point light in the scene
  44487. * @param scene The scene the lights belongs to
  44488. */
  44489. function PointLight(name, position, scene) {
  44490. var _this = _super.call(this, name, scene) || this;
  44491. _this._shadowAngle = Math.PI / 2;
  44492. _this.position = position;
  44493. return _this;
  44494. }
  44495. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  44496. /**
  44497. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44498. * This specifies what angle the shadow will use to be created.
  44499. *
  44500. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  44501. */
  44502. get: function () {
  44503. return this._shadowAngle;
  44504. },
  44505. /**
  44506. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44507. * This specifies what angle the shadow will use to be created.
  44508. *
  44509. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  44510. */
  44511. set: function (value) {
  44512. this._shadowAngle = value;
  44513. this.forceProjectionMatrixCompute();
  44514. },
  44515. enumerable: true,
  44516. configurable: true
  44517. });
  44518. Object.defineProperty(PointLight.prototype, "direction", {
  44519. /**
  44520. * Gets the direction if it has been set.
  44521. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44522. */
  44523. get: function () {
  44524. return this._direction;
  44525. },
  44526. /**
  44527. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44528. */
  44529. set: function (value) {
  44530. var previousNeedCube = this.needCube();
  44531. this._direction = value;
  44532. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  44533. this._shadowGenerator.recreateShadowMap();
  44534. }
  44535. },
  44536. enumerable: true,
  44537. configurable: true
  44538. });
  44539. /**
  44540. * Returns the string "PointLight"
  44541. * @returns the class name
  44542. */
  44543. PointLight.prototype.getClassName = function () {
  44544. return "PointLight";
  44545. };
  44546. /**
  44547. * Returns the integer 0.
  44548. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44549. */
  44550. PointLight.prototype.getTypeID = function () {
  44551. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  44552. };
  44553. /**
  44554. * Specifies wether or not the shadowmap should be a cube texture.
  44555. * @returns true if the shadowmap needs to be a cube texture.
  44556. */
  44557. PointLight.prototype.needCube = function () {
  44558. return !this.direction;
  44559. };
  44560. /**
  44561. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  44562. * @param faceIndex The index of the face we are computed the direction to generate shadow
  44563. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  44564. */
  44565. PointLight.prototype.getShadowDirection = function (faceIndex) {
  44566. if (this.direction) {
  44567. return _super.prototype.getShadowDirection.call(this, faceIndex);
  44568. }
  44569. else {
  44570. switch (faceIndex) {
  44571. case 0:
  44572. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  44573. case 1:
  44574. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  44575. case 2:
  44576. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  44577. case 3:
  44578. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  44579. case 4:
  44580. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  44581. case 5:
  44582. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  44583. }
  44584. }
  44585. return BABYLON.Vector3.Zero();
  44586. };
  44587. /**
  44588. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  44589. * - fov = PI / 2
  44590. * - aspect ratio : 1.0
  44591. * - z-near and far equal to the active camera minZ and maxZ.
  44592. * Returns the PointLight.
  44593. */
  44594. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44595. var activeCamera = this.getScene().activeCamera;
  44596. if (!activeCamera) {
  44597. return;
  44598. }
  44599. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  44600. };
  44601. PointLight.prototype._buildUniformLayout = function () {
  44602. this._uniformBuffer.addUniform("vLightData", 4);
  44603. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  44604. this._uniformBuffer.addUniform("vLightSpecular", 3);
  44605. this._uniformBuffer.addUniform("shadowsInfo", 3);
  44606. this._uniformBuffer.addUniform("depthValues", 2);
  44607. this._uniformBuffer.create();
  44608. };
  44609. /**
  44610. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  44611. * @param effect The effect to update
  44612. * @param lightIndex The index of the light in the effect to update
  44613. * @returns The point light
  44614. */
  44615. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  44616. if (this.computeTransformedInformation()) {
  44617. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  44618. return this;
  44619. }
  44620. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  44621. return this;
  44622. };
  44623. __decorate([
  44624. BABYLON.serialize()
  44625. ], PointLight.prototype, "shadowAngle", null);
  44626. return PointLight;
  44627. }(BABYLON.ShadowLight));
  44628. BABYLON.PointLight = PointLight;
  44629. })(BABYLON || (BABYLON = {}));
  44630. //# sourceMappingURL=babylon.pointLight.js.map
  44631. var BABYLON;
  44632. (function (BABYLON) {
  44633. /**
  44634. * A directional light is defined by a direction (what a surprise!).
  44635. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  44636. * 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.
  44637. * Documentation: https://doc.babylonjs.com/babylon101/lights
  44638. */
  44639. var DirectionalLight = /** @class */ (function (_super) {
  44640. __extends(DirectionalLight, _super);
  44641. /**
  44642. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  44643. * The directional light is emitted from everywhere in the given direction.
  44644. * It can cast shawdows.
  44645. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44646. * @param name The friendly name of the light
  44647. * @param direction The direction of the light
  44648. * @param scene The scene the light belongs to
  44649. */
  44650. function DirectionalLight(name, direction, scene) {
  44651. var _this = _super.call(this, name, scene) || this;
  44652. _this._shadowFrustumSize = 0;
  44653. _this._shadowOrthoScale = 0.5;
  44654. /**
  44655. * Automatically compute the projection matrix to best fit (including all the casters)
  44656. * on each frame.
  44657. */
  44658. _this.autoUpdateExtends = true;
  44659. // Cache
  44660. _this._orthoLeft = Number.MAX_VALUE;
  44661. _this._orthoRight = Number.MIN_VALUE;
  44662. _this._orthoTop = Number.MIN_VALUE;
  44663. _this._orthoBottom = Number.MAX_VALUE;
  44664. _this.position = direction.scale(-1.0);
  44665. _this.direction = direction;
  44666. return _this;
  44667. }
  44668. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  44669. /**
  44670. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  44671. */
  44672. get: function () {
  44673. return this._shadowFrustumSize;
  44674. },
  44675. /**
  44676. * Specifies a fix frustum size for the shadow generation.
  44677. */
  44678. set: function (value) {
  44679. this._shadowFrustumSize = value;
  44680. this.forceProjectionMatrixCompute();
  44681. },
  44682. enumerable: true,
  44683. configurable: true
  44684. });
  44685. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  44686. /**
  44687. * Gets the shadow projection scale against the optimal computed one.
  44688. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  44689. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  44690. */
  44691. get: function () {
  44692. return this._shadowOrthoScale;
  44693. },
  44694. /**
  44695. * Sets the shadow projection scale against the optimal computed one.
  44696. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  44697. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  44698. */
  44699. set: function (value) {
  44700. this._shadowOrthoScale = value;
  44701. this.forceProjectionMatrixCompute();
  44702. },
  44703. enumerable: true,
  44704. configurable: true
  44705. });
  44706. /**
  44707. * Returns the string "DirectionalLight".
  44708. * @return The class name
  44709. */
  44710. DirectionalLight.prototype.getClassName = function () {
  44711. return "DirectionalLight";
  44712. };
  44713. /**
  44714. * Returns the integer 1.
  44715. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44716. */
  44717. DirectionalLight.prototype.getTypeID = function () {
  44718. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  44719. };
  44720. /**
  44721. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  44722. * Returns the DirectionalLight Shadow projection matrix.
  44723. */
  44724. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44725. if (this.shadowFrustumSize > 0) {
  44726. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  44727. }
  44728. else {
  44729. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  44730. }
  44731. };
  44732. /**
  44733. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  44734. * Returns the DirectionalLight Shadow projection matrix.
  44735. */
  44736. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  44737. var activeCamera = this.getScene().activeCamera;
  44738. if (!activeCamera) {
  44739. return;
  44740. }
  44741. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  44742. };
  44743. /**
  44744. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  44745. * Returns the DirectionalLight Shadow projection matrix.
  44746. */
  44747. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44748. var activeCamera = this.getScene().activeCamera;
  44749. if (!activeCamera) {
  44750. return;
  44751. }
  44752. // Check extends
  44753. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  44754. var tempVector3 = BABYLON.Vector3.Zero();
  44755. this._orthoLeft = Number.MAX_VALUE;
  44756. this._orthoRight = Number.MIN_VALUE;
  44757. this._orthoTop = Number.MIN_VALUE;
  44758. this._orthoBottom = Number.MAX_VALUE;
  44759. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  44760. var mesh = renderList[meshIndex];
  44761. if (!mesh) {
  44762. continue;
  44763. }
  44764. var boundingInfo = mesh.getBoundingInfo();
  44765. var boundingBox = boundingInfo.boundingBox;
  44766. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  44767. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  44768. if (tempVector3.x < this._orthoLeft)
  44769. this._orthoLeft = tempVector3.x;
  44770. if (tempVector3.y < this._orthoBottom)
  44771. this._orthoBottom = tempVector3.y;
  44772. if (tempVector3.x > this._orthoRight)
  44773. this._orthoRight = tempVector3.x;
  44774. if (tempVector3.y > this._orthoTop)
  44775. this._orthoTop = tempVector3.y;
  44776. }
  44777. }
  44778. }
  44779. var xOffset = this._orthoRight - this._orthoLeft;
  44780. var yOffset = this._orthoTop - this._orthoBottom;
  44781. 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);
  44782. };
  44783. DirectionalLight.prototype._buildUniformLayout = function () {
  44784. this._uniformBuffer.addUniform("vLightData", 4);
  44785. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  44786. this._uniformBuffer.addUniform("vLightSpecular", 3);
  44787. this._uniformBuffer.addUniform("shadowsInfo", 3);
  44788. this._uniformBuffer.addUniform("depthValues", 2);
  44789. this._uniformBuffer.create();
  44790. };
  44791. /**
  44792. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  44793. * @param effect The effect to update
  44794. * @param lightIndex The index of the light in the effect to update
  44795. * @returns The directional light
  44796. */
  44797. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  44798. if (this.computeTransformedInformation()) {
  44799. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  44800. return this;
  44801. }
  44802. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  44803. return this;
  44804. };
  44805. /**
  44806. * Gets the minZ used for shadow according to both the scene and the light.
  44807. *
  44808. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  44809. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  44810. * @param activeCamera The camera we are returning the min for
  44811. * @returns the depth min z
  44812. */
  44813. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  44814. return 1;
  44815. };
  44816. /**
  44817. * Gets the maxZ used for shadow according to both the scene and the light.
  44818. *
  44819. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  44820. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  44821. * @param activeCamera The camera we are returning the max for
  44822. * @returns the depth max z
  44823. */
  44824. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  44825. return 1;
  44826. };
  44827. __decorate([
  44828. BABYLON.serialize()
  44829. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  44830. __decorate([
  44831. BABYLON.serialize()
  44832. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  44833. __decorate([
  44834. BABYLON.serialize()
  44835. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  44836. return DirectionalLight;
  44837. }(BABYLON.ShadowLight));
  44838. BABYLON.DirectionalLight = DirectionalLight;
  44839. })(BABYLON || (BABYLON = {}));
  44840. //# sourceMappingURL=babylon.directionalLight.js.map
  44841. var BABYLON;
  44842. (function (BABYLON) {
  44843. /**
  44844. * A spot light is defined by a position, a direction, an angle, and an exponent.
  44845. * These values define a cone of light starting from the position, emitting toward the direction.
  44846. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  44847. * and the exponent defines the speed of the decay of the light with distance (reach).
  44848. * Documentation: https://doc.babylonjs.com/babylon101/lights
  44849. */
  44850. var SpotLight = /** @class */ (function (_super) {
  44851. __extends(SpotLight, _super);
  44852. /**
  44853. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  44854. * It can cast shadows.
  44855. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44856. * @param name The light friendly name
  44857. * @param position The position of the spot light in the scene
  44858. * @param direction The direction of the light in the scene
  44859. * @param angle The cone angle of the light in Radians
  44860. * @param exponent The light decay speed with the distance from the emission spot
  44861. * @param scene The scene the lights belongs to
  44862. */
  44863. function SpotLight(name, position, direction, angle, exponent, scene) {
  44864. var _this = _super.call(this, name, scene) || this;
  44865. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  44866. _this._projectionTextureLightNear = 1e-6;
  44867. _this._projectionTextureLightFar = 1000.0;
  44868. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  44869. _this._projectionTextureViewLightDirty = true;
  44870. _this._projectionTextureProjectionLightDirty = true;
  44871. _this._projectionTextureDirty = true;
  44872. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  44873. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  44874. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  44875. _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);
  44876. _this.position = position;
  44877. _this.direction = direction;
  44878. _this.angle = angle;
  44879. _this.exponent = exponent;
  44880. return _this;
  44881. }
  44882. Object.defineProperty(SpotLight.prototype, "angle", {
  44883. /**
  44884. * Gets the cone angle of the spot light in Radians.
  44885. */
  44886. get: function () {
  44887. return this._angle;
  44888. },
  44889. /**
  44890. * Sets the cone angle of the spot light in Radians.
  44891. */
  44892. set: function (value) {
  44893. this._angle = value;
  44894. this._projectionTextureProjectionLightDirty = true;
  44895. this.forceProjectionMatrixCompute();
  44896. },
  44897. enumerable: true,
  44898. configurable: true
  44899. });
  44900. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  44901. /**
  44902. * Allows scaling the angle of the light for shadow generation only.
  44903. */
  44904. get: function () {
  44905. return this._shadowAngleScale;
  44906. },
  44907. /**
  44908. * Allows scaling the angle of the light for shadow generation only.
  44909. */
  44910. set: function (value) {
  44911. this._shadowAngleScale = value;
  44912. this.forceProjectionMatrixCompute();
  44913. },
  44914. enumerable: true,
  44915. configurable: true
  44916. });
  44917. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  44918. /**
  44919. * Allows reading the projecton texture
  44920. */
  44921. get: function () {
  44922. return this._projectionTextureMatrix;
  44923. },
  44924. enumerable: true,
  44925. configurable: true
  44926. });
  44927. ;
  44928. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  44929. /**
  44930. * Gets the near clip of the Spotlight for texture projection.
  44931. */
  44932. get: function () {
  44933. return this._projectionTextureLightNear;
  44934. },
  44935. /**
  44936. * Sets the near clip of the Spotlight for texture projection.
  44937. */
  44938. set: function (value) {
  44939. this._projectionTextureLightNear = value;
  44940. this._projectionTextureProjectionLightDirty = true;
  44941. },
  44942. enumerable: true,
  44943. configurable: true
  44944. });
  44945. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  44946. /**
  44947. * Gets the far clip of the Spotlight for texture projection.
  44948. */
  44949. get: function () {
  44950. return this._projectionTextureLightFar;
  44951. },
  44952. /**
  44953. * Sets the far clip of the Spotlight for texture projection.
  44954. */
  44955. set: function (value) {
  44956. this._projectionTextureLightFar = value;
  44957. this._projectionTextureProjectionLightDirty = true;
  44958. },
  44959. enumerable: true,
  44960. configurable: true
  44961. });
  44962. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  44963. /**
  44964. * Gets the Up vector of the Spotlight for texture projection.
  44965. */
  44966. get: function () {
  44967. return this._projectionTextureUpDirection;
  44968. },
  44969. /**
  44970. * Sets the Up vector of the Spotlight for texture projection.
  44971. */
  44972. set: function (value) {
  44973. this._projectionTextureUpDirection = value;
  44974. this._projectionTextureProjectionLightDirty = true;
  44975. },
  44976. enumerable: true,
  44977. configurable: true
  44978. });
  44979. ;
  44980. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  44981. /**
  44982. * Gets the projection texture of the light.
  44983. */
  44984. get: function () {
  44985. return this._projectionTexture;
  44986. },
  44987. /**
  44988. * Sets the projection texture of the light.
  44989. */
  44990. set: function (value) {
  44991. this._projectionTexture = value;
  44992. this._projectionTextureDirty = true;
  44993. },
  44994. enumerable: true,
  44995. configurable: true
  44996. });
  44997. /**
  44998. * Returns the string "SpotLight".
  44999. * @returns the class name
  45000. */
  45001. SpotLight.prototype.getClassName = function () {
  45002. return "SpotLight";
  45003. };
  45004. /**
  45005. * Returns the integer 2.
  45006. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45007. */
  45008. SpotLight.prototype.getTypeID = function () {
  45009. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  45010. };
  45011. /**
  45012. * Overrides the direction setter to recompute the projection texture view light Matrix.
  45013. */
  45014. SpotLight.prototype._setDirection = function (value) {
  45015. _super.prototype._setDirection.call(this, value);
  45016. this._projectionTextureViewLightDirty = true;
  45017. };
  45018. /**
  45019. * Overrides the position setter to recompute the projection texture view light Matrix.
  45020. */
  45021. SpotLight.prototype._setPosition = function (value) {
  45022. _super.prototype._setPosition.call(this, value);
  45023. this._projectionTextureViewLightDirty = true;
  45024. };
  45025. /**
  45026. * 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.
  45027. * Returns the SpotLight.
  45028. */
  45029. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45030. var activeCamera = this.getScene().activeCamera;
  45031. if (!activeCamera) {
  45032. return;
  45033. }
  45034. this._shadowAngleScale = this._shadowAngleScale || 1;
  45035. var angle = this._shadowAngleScale * this._angle;
  45036. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45037. };
  45038. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  45039. this._projectionTextureViewLightDirty = false;
  45040. this._projectionTextureDirty = true;
  45041. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  45042. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  45043. };
  45044. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  45045. this._projectionTextureProjectionLightDirty = false;
  45046. this._projectionTextureDirty = true;
  45047. var light_far = this.projectionTextureLightFar;
  45048. var light_near = this.projectionTextureLightNear;
  45049. var P = light_far / (light_far - light_near);
  45050. var Q = -P * light_near;
  45051. var S = 1.0 / Math.tan(this._angle / 2.0);
  45052. var A = 1.0;
  45053. 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);
  45054. };
  45055. /**
  45056. * Main function for light texture projection matrix computing.
  45057. */
  45058. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  45059. this._projectionTextureDirty = false;
  45060. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  45061. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  45062. };
  45063. SpotLight.prototype._buildUniformLayout = function () {
  45064. this._uniformBuffer.addUniform("vLightData", 4);
  45065. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45066. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45067. this._uniformBuffer.addUniform("vLightDirection", 3);
  45068. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45069. this._uniformBuffer.addUniform("depthValues", 2);
  45070. this._uniformBuffer.create();
  45071. };
  45072. /**
  45073. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  45074. * @param effect The effect to update
  45075. * @param lightIndex The index of the light in the effect to update
  45076. * @returns The spot light
  45077. */
  45078. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  45079. var normalizeDirection;
  45080. if (this.computeTransformedInformation()) {
  45081. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  45082. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  45083. }
  45084. else {
  45085. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  45086. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45087. }
  45088. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  45089. if (this.projectionTexture && this.projectionTexture.isReady()) {
  45090. if (this._projectionTextureViewLightDirty) {
  45091. this._computeProjectionTextureViewLightMatrix();
  45092. }
  45093. if (this._projectionTextureProjectionLightDirty) {
  45094. this._computeProjectionTextureProjectionLightMatrix();
  45095. }
  45096. if (this._projectionTextureDirty) {
  45097. this._computeProjectionTextureMatrix();
  45098. }
  45099. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  45100. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  45101. }
  45102. return this;
  45103. };
  45104. /**
  45105. * Disposes the light and the associated resources.
  45106. */
  45107. SpotLight.prototype.dispose = function () {
  45108. _super.prototype.dispose.call(this);
  45109. if (this._projectionTexture) {
  45110. this._projectionTexture.dispose();
  45111. }
  45112. };
  45113. __decorate([
  45114. BABYLON.serialize()
  45115. ], SpotLight.prototype, "angle", null);
  45116. __decorate([
  45117. BABYLON.serialize()
  45118. ], SpotLight.prototype, "shadowAngleScale", null);
  45119. __decorate([
  45120. BABYLON.serialize()
  45121. ], SpotLight.prototype, "exponent", void 0);
  45122. __decorate([
  45123. BABYLON.serialize()
  45124. ], SpotLight.prototype, "projectionTextureLightNear", null);
  45125. __decorate([
  45126. BABYLON.serialize()
  45127. ], SpotLight.prototype, "projectionTextureLightFar", null);
  45128. __decorate([
  45129. BABYLON.serialize()
  45130. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  45131. __decorate([
  45132. BABYLON.serializeAsTexture("projectedLightTexture")
  45133. ], SpotLight.prototype, "_projectionTexture", void 0);
  45134. return SpotLight;
  45135. }(BABYLON.ShadowLight));
  45136. BABYLON.SpotLight = SpotLight;
  45137. })(BABYLON || (BABYLON = {}));
  45138. //# sourceMappingURL=babylon.spotLight.js.map
  45139. var BABYLON;
  45140. (function (BABYLON) {
  45141. var AnimationRange = /** @class */ (function () {
  45142. function AnimationRange(name, from, to) {
  45143. this.name = name;
  45144. this.from = from;
  45145. this.to = to;
  45146. }
  45147. AnimationRange.prototype.clone = function () {
  45148. return new AnimationRange(this.name, this.from, this.to);
  45149. };
  45150. return AnimationRange;
  45151. }());
  45152. BABYLON.AnimationRange = AnimationRange;
  45153. /**
  45154. * Composed of a frame, and an action function
  45155. */
  45156. var AnimationEvent = /** @class */ (function () {
  45157. function AnimationEvent(frame, action, onlyOnce) {
  45158. this.frame = frame;
  45159. this.action = action;
  45160. this.onlyOnce = onlyOnce;
  45161. this.isDone = false;
  45162. }
  45163. return AnimationEvent;
  45164. }());
  45165. BABYLON.AnimationEvent = AnimationEvent;
  45166. var PathCursor = /** @class */ (function () {
  45167. function PathCursor(path) {
  45168. this.path = path;
  45169. this._onchange = new Array();
  45170. this.value = 0;
  45171. this.animations = new Array();
  45172. }
  45173. PathCursor.prototype.getPoint = function () {
  45174. var point = this.path.getPointAtLengthPosition(this.value);
  45175. return new BABYLON.Vector3(point.x, 0, point.y);
  45176. };
  45177. PathCursor.prototype.moveAhead = function (step) {
  45178. if (step === void 0) { step = 0.002; }
  45179. this.move(step);
  45180. return this;
  45181. };
  45182. PathCursor.prototype.moveBack = function (step) {
  45183. if (step === void 0) { step = 0.002; }
  45184. this.move(-step);
  45185. return this;
  45186. };
  45187. PathCursor.prototype.move = function (step) {
  45188. if (Math.abs(step) > 1) {
  45189. throw "step size should be less than 1.";
  45190. }
  45191. this.value += step;
  45192. this.ensureLimits();
  45193. this.raiseOnChange();
  45194. return this;
  45195. };
  45196. PathCursor.prototype.ensureLimits = function () {
  45197. while (this.value > 1) {
  45198. this.value -= 1;
  45199. }
  45200. while (this.value < 0) {
  45201. this.value += 1;
  45202. }
  45203. return this;
  45204. };
  45205. // used by animation engine
  45206. PathCursor.prototype.raiseOnChange = function () {
  45207. var _this = this;
  45208. this._onchange.forEach(function (f) { return f(_this); });
  45209. return this;
  45210. };
  45211. PathCursor.prototype.onchange = function (f) {
  45212. this._onchange.push(f);
  45213. return this;
  45214. };
  45215. return PathCursor;
  45216. }());
  45217. BABYLON.PathCursor = PathCursor;
  45218. var AnimationKeyInterpolation;
  45219. (function (AnimationKeyInterpolation) {
  45220. /**
  45221. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  45222. */
  45223. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  45224. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  45225. var Animation = /** @class */ (function () {
  45226. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  45227. this.name = name;
  45228. this.targetProperty = targetProperty;
  45229. this.framePerSecond = framePerSecond;
  45230. this.dataType = dataType;
  45231. this.loopMode = loopMode;
  45232. this.enableBlending = enableBlending;
  45233. this._runtimeAnimations = new Array();
  45234. // The set of event that will be linked to this animation
  45235. this._events = new Array();
  45236. this.blendingSpeed = 0.01;
  45237. this._ranges = {};
  45238. this.targetPropertyPath = targetProperty.split(".");
  45239. this.dataType = dataType;
  45240. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  45241. }
  45242. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  45243. var dataType = undefined;
  45244. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  45245. dataType = Animation.ANIMATIONTYPE_FLOAT;
  45246. }
  45247. else if (from instanceof BABYLON.Quaternion) {
  45248. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  45249. }
  45250. else if (from instanceof BABYLON.Vector3) {
  45251. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  45252. }
  45253. else if (from instanceof BABYLON.Vector2) {
  45254. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  45255. }
  45256. else if (from instanceof BABYLON.Color3) {
  45257. dataType = Animation.ANIMATIONTYPE_COLOR3;
  45258. }
  45259. else if (from instanceof BABYLON.Size) {
  45260. dataType = Animation.ANIMATIONTYPE_SIZE;
  45261. }
  45262. if (dataType == undefined) {
  45263. return null;
  45264. }
  45265. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  45266. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  45267. animation.setKeys(keys);
  45268. if (easingFunction !== undefined) {
  45269. animation.setEasingFunction(easingFunction);
  45270. }
  45271. return animation;
  45272. };
  45273. /**
  45274. * Sets up an animation.
  45275. * @param property the property to animate
  45276. * @param animationType the animation type to apply
  45277. * @param easingFunction the easing function used in the animation
  45278. * @returns The created animation
  45279. */
  45280. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  45281. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  45282. animation.setEasingFunction(easingFunction);
  45283. return animation;
  45284. };
  45285. /**
  45286. * Create and start an animation on a node
  45287. * @param {string} name defines the name of the global animation that will be run on all nodes
  45288. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45289. * @param {string} targetProperty defines property to animate
  45290. * @param {number} framePerSecond defines the number of frame per second yo use
  45291. * @param {number} totalFrame defines the number of frames in total
  45292. * @param {any} from defines the initial value
  45293. * @param {any} to defines the final value
  45294. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45295. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45296. * @param onAnimationEnd defines the callback to call when animation end
  45297. * @returns the animatable created for this animation
  45298. */
  45299. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45300. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45301. if (!animation) {
  45302. return null;
  45303. }
  45304. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45305. };
  45306. /**
  45307. * Create and start an animation on a node and its descendants
  45308. * @param {string} name defines the name of the global animation that will be run on all nodes
  45309. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45310. * @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.
  45311. * @param {string} targetProperty defines property to animate
  45312. * @param {number} framePerSecond defines the number of frame per second yo use
  45313. * @param {number} totalFrame defines the number of frames in total
  45314. * @param {any} from defines the initial value
  45315. * @param {any} to defines the final value
  45316. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45317. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45318. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  45319. * @returns the list of animatables created for all nodes
  45320. * @example https://www.babylonjs-playground.com/#MH0VLI
  45321. */
  45322. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45323. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45324. if (!animation) {
  45325. return null;
  45326. }
  45327. var scene = node.getScene();
  45328. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45329. };
  45330. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45331. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45332. if (!animation) {
  45333. return null;
  45334. }
  45335. node.animations.push(animation);
  45336. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45337. };
  45338. /**
  45339. * Transition property of the Camera to the target Value.
  45340. * @param property The property to transition
  45341. * @param targetValue The target Value of the property
  45342. * @param host The object where the property to animate belongs
  45343. * @param scene Scene used to run the animation
  45344. * @param frameRate Framerate (in frame/s) to use
  45345. * @param transition The transition type we want to use
  45346. * @param duration The duration of the animation, in milliseconds
  45347. * @param onAnimationEnd Call back trigger at the end of the animation.
  45348. */
  45349. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  45350. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  45351. if (duration <= 0) {
  45352. host[property] = targetValue;
  45353. if (onAnimationEnd) {
  45354. onAnimationEnd();
  45355. }
  45356. return null;
  45357. }
  45358. var endFrame = frameRate * (duration / 1000);
  45359. transition.setKeys([{
  45360. frame: 0,
  45361. value: host[property].clone ? host[property].clone() : host[property]
  45362. },
  45363. {
  45364. frame: endFrame,
  45365. value: targetValue
  45366. }]);
  45367. if (!host.animations) {
  45368. host.animations = [];
  45369. }
  45370. host.animations.push(transition);
  45371. var animation = scene.beginAnimation(host, 0, endFrame, false);
  45372. animation.onAnimationEnd = onAnimationEnd;
  45373. return animation;
  45374. };
  45375. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  45376. /**
  45377. * Return the array of runtime animations currently using this animation
  45378. */
  45379. get: function () {
  45380. return this._runtimeAnimations;
  45381. },
  45382. enumerable: true,
  45383. configurable: true
  45384. });
  45385. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  45386. get: function () {
  45387. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  45388. var runtimeAnimation = _a[_i];
  45389. if (!runtimeAnimation.isStopped) {
  45390. return true;
  45391. }
  45392. }
  45393. return false;
  45394. },
  45395. enumerable: true,
  45396. configurable: true
  45397. });
  45398. // Methods
  45399. /**
  45400. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  45401. */
  45402. Animation.prototype.toString = function (fullDetails) {
  45403. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  45404. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  45405. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  45406. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  45407. if (fullDetails) {
  45408. ret += ", Ranges: {";
  45409. var first = true;
  45410. for (var name in this._ranges) {
  45411. if (first) {
  45412. ret += ", ";
  45413. first = false;
  45414. }
  45415. ret += name;
  45416. }
  45417. ret += "}";
  45418. }
  45419. return ret;
  45420. };
  45421. /**
  45422. * Add an event to this animation.
  45423. */
  45424. Animation.prototype.addEvent = function (event) {
  45425. this._events.push(event);
  45426. };
  45427. /**
  45428. * Remove all events found at the given frame
  45429. * @param frame
  45430. */
  45431. Animation.prototype.removeEvents = function (frame) {
  45432. for (var index = 0; index < this._events.length; index++) {
  45433. if (this._events[index].frame === frame) {
  45434. this._events.splice(index, 1);
  45435. index--;
  45436. }
  45437. }
  45438. };
  45439. Animation.prototype.getEvents = function () {
  45440. return this._events;
  45441. };
  45442. Animation.prototype.createRange = function (name, from, to) {
  45443. // check name not already in use; could happen for bones after serialized
  45444. if (!this._ranges[name]) {
  45445. this._ranges[name] = new AnimationRange(name, from, to);
  45446. }
  45447. };
  45448. Animation.prototype.deleteRange = function (name, deleteFrames) {
  45449. if (deleteFrames === void 0) { deleteFrames = true; }
  45450. var range = this._ranges[name];
  45451. if (!range) {
  45452. return;
  45453. }
  45454. if (deleteFrames) {
  45455. var from = range.from;
  45456. var to = range.to;
  45457. // this loop MUST go high to low for multiple splices to work
  45458. for (var key = this._keys.length - 1; key >= 0; key--) {
  45459. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  45460. this._keys.splice(key, 1);
  45461. }
  45462. }
  45463. }
  45464. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  45465. };
  45466. Animation.prototype.getRange = function (name) {
  45467. return this._ranges[name];
  45468. };
  45469. Animation.prototype.getKeys = function () {
  45470. return this._keys;
  45471. };
  45472. Animation.prototype.getHighestFrame = function () {
  45473. var ret = 0;
  45474. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  45475. if (ret < this._keys[key].frame) {
  45476. ret = this._keys[key].frame;
  45477. }
  45478. }
  45479. return ret;
  45480. };
  45481. Animation.prototype.getEasingFunction = function () {
  45482. return this._easingFunction;
  45483. };
  45484. Animation.prototype.setEasingFunction = function (easingFunction) {
  45485. this._easingFunction = easingFunction;
  45486. };
  45487. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  45488. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  45489. };
  45490. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45491. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  45492. };
  45493. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  45494. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  45495. };
  45496. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45497. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  45498. };
  45499. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  45500. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  45501. };
  45502. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45503. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  45504. };
  45505. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  45506. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  45507. };
  45508. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45509. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  45510. };
  45511. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  45512. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  45513. };
  45514. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  45515. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  45516. };
  45517. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  45518. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  45519. };
  45520. Animation.prototype.clone = function () {
  45521. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  45522. clone.enableBlending = this.enableBlending;
  45523. clone.blendingSpeed = this.blendingSpeed;
  45524. if (this._keys) {
  45525. clone.setKeys(this._keys);
  45526. }
  45527. if (this._ranges) {
  45528. clone._ranges = {};
  45529. for (var name in this._ranges) {
  45530. var range = this._ranges[name];
  45531. if (!range) {
  45532. continue;
  45533. }
  45534. clone._ranges[name] = range.clone();
  45535. }
  45536. }
  45537. return clone;
  45538. };
  45539. Animation.prototype.setKeys = function (values) {
  45540. this._keys = values.slice(0);
  45541. };
  45542. Animation.prototype.serialize = function () {
  45543. var serializationObject = {};
  45544. serializationObject.name = this.name;
  45545. serializationObject.property = this.targetProperty;
  45546. serializationObject.framePerSecond = this.framePerSecond;
  45547. serializationObject.dataType = this.dataType;
  45548. serializationObject.loopBehavior = this.loopMode;
  45549. serializationObject.enableBlending = this.enableBlending;
  45550. serializationObject.blendingSpeed = this.blendingSpeed;
  45551. var dataType = this.dataType;
  45552. serializationObject.keys = [];
  45553. var keys = this.getKeys();
  45554. for (var index = 0; index < keys.length; index++) {
  45555. var animationKey = keys[index];
  45556. var key = {};
  45557. key.frame = animationKey.frame;
  45558. switch (dataType) {
  45559. case Animation.ANIMATIONTYPE_FLOAT:
  45560. key.values = [animationKey.value];
  45561. break;
  45562. case Animation.ANIMATIONTYPE_QUATERNION:
  45563. case Animation.ANIMATIONTYPE_MATRIX:
  45564. case Animation.ANIMATIONTYPE_VECTOR3:
  45565. case Animation.ANIMATIONTYPE_COLOR3:
  45566. key.values = animationKey.value.asArray();
  45567. break;
  45568. }
  45569. serializationObject.keys.push(key);
  45570. }
  45571. serializationObject.ranges = [];
  45572. for (var name in this._ranges) {
  45573. var source = this._ranges[name];
  45574. if (!source) {
  45575. continue;
  45576. }
  45577. var range = {};
  45578. range.name = name;
  45579. range.from = source.from;
  45580. range.to = source.to;
  45581. serializationObject.ranges.push(range);
  45582. }
  45583. return serializationObject;
  45584. };
  45585. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  45586. get: function () {
  45587. return Animation._ANIMATIONTYPE_FLOAT;
  45588. },
  45589. enumerable: true,
  45590. configurable: true
  45591. });
  45592. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  45593. get: function () {
  45594. return Animation._ANIMATIONTYPE_VECTOR3;
  45595. },
  45596. enumerable: true,
  45597. configurable: true
  45598. });
  45599. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  45600. get: function () {
  45601. return Animation._ANIMATIONTYPE_VECTOR2;
  45602. },
  45603. enumerable: true,
  45604. configurable: true
  45605. });
  45606. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  45607. get: function () {
  45608. return Animation._ANIMATIONTYPE_SIZE;
  45609. },
  45610. enumerable: true,
  45611. configurable: true
  45612. });
  45613. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  45614. get: function () {
  45615. return Animation._ANIMATIONTYPE_QUATERNION;
  45616. },
  45617. enumerable: true,
  45618. configurable: true
  45619. });
  45620. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  45621. get: function () {
  45622. return Animation._ANIMATIONTYPE_MATRIX;
  45623. },
  45624. enumerable: true,
  45625. configurable: true
  45626. });
  45627. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  45628. get: function () {
  45629. return Animation._ANIMATIONTYPE_COLOR3;
  45630. },
  45631. enumerable: true,
  45632. configurable: true
  45633. });
  45634. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  45635. get: function () {
  45636. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  45637. },
  45638. enumerable: true,
  45639. configurable: true
  45640. });
  45641. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  45642. get: function () {
  45643. return Animation._ANIMATIONLOOPMODE_CYCLE;
  45644. },
  45645. enumerable: true,
  45646. configurable: true
  45647. });
  45648. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  45649. get: function () {
  45650. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  45651. },
  45652. enumerable: true,
  45653. configurable: true
  45654. });
  45655. Animation.Parse = function (parsedAnimation) {
  45656. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  45657. var dataType = parsedAnimation.dataType;
  45658. var keys = [];
  45659. var data;
  45660. var index;
  45661. if (parsedAnimation.enableBlending) {
  45662. animation.enableBlending = parsedAnimation.enableBlending;
  45663. }
  45664. if (parsedAnimation.blendingSpeed) {
  45665. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  45666. }
  45667. for (index = 0; index < parsedAnimation.keys.length; index++) {
  45668. var key = parsedAnimation.keys[index];
  45669. var inTangent;
  45670. var outTangent;
  45671. switch (dataType) {
  45672. case Animation.ANIMATIONTYPE_FLOAT:
  45673. data = key.values[0];
  45674. if (key.values.length >= 1) {
  45675. inTangent = key.values[1];
  45676. }
  45677. if (key.values.length >= 2) {
  45678. outTangent = key.values[2];
  45679. }
  45680. break;
  45681. case Animation.ANIMATIONTYPE_QUATERNION:
  45682. data = BABYLON.Quaternion.FromArray(key.values);
  45683. if (key.values.length >= 8) {
  45684. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  45685. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  45686. inTangent = _inTangent;
  45687. }
  45688. }
  45689. if (key.values.length >= 12) {
  45690. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  45691. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  45692. outTangent = _outTangent;
  45693. }
  45694. }
  45695. break;
  45696. case Animation.ANIMATIONTYPE_MATRIX:
  45697. data = BABYLON.Matrix.FromArray(key.values);
  45698. break;
  45699. case Animation.ANIMATIONTYPE_COLOR3:
  45700. data = BABYLON.Color3.FromArray(key.values);
  45701. break;
  45702. case Animation.ANIMATIONTYPE_VECTOR3:
  45703. default:
  45704. data = BABYLON.Vector3.FromArray(key.values);
  45705. break;
  45706. }
  45707. var keyData = {};
  45708. keyData.frame = key.frame;
  45709. keyData.value = data;
  45710. if (inTangent != undefined) {
  45711. keyData.inTangent = inTangent;
  45712. }
  45713. if (outTangent != undefined) {
  45714. keyData.outTangent = outTangent;
  45715. }
  45716. keys.push(keyData);
  45717. }
  45718. animation.setKeys(keys);
  45719. if (parsedAnimation.ranges) {
  45720. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  45721. data = parsedAnimation.ranges[index];
  45722. animation.createRange(data.name, data.from, data.to);
  45723. }
  45724. }
  45725. return animation;
  45726. };
  45727. Animation.AppendSerializedAnimations = function (source, destination) {
  45728. if (source.animations) {
  45729. destination.animations = [];
  45730. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  45731. var animation = source.animations[animationIndex];
  45732. destination.animations.push(animation.serialize());
  45733. }
  45734. }
  45735. };
  45736. Animation.AllowMatricesInterpolation = false;
  45737. // Statics
  45738. Animation._ANIMATIONTYPE_FLOAT = 0;
  45739. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  45740. Animation._ANIMATIONTYPE_QUATERNION = 2;
  45741. Animation._ANIMATIONTYPE_MATRIX = 3;
  45742. Animation._ANIMATIONTYPE_COLOR3 = 4;
  45743. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  45744. Animation._ANIMATIONTYPE_SIZE = 6;
  45745. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  45746. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  45747. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  45748. return Animation;
  45749. }());
  45750. BABYLON.Animation = Animation;
  45751. })(BABYLON || (BABYLON = {}));
  45752. //# sourceMappingURL=babylon.animation.js.map
  45753. var BABYLON;
  45754. (function (BABYLON) {
  45755. /**
  45756. * This class defines the direct association between an animation and a target
  45757. */
  45758. var TargetedAnimation = /** @class */ (function () {
  45759. function TargetedAnimation() {
  45760. }
  45761. return TargetedAnimation;
  45762. }());
  45763. BABYLON.TargetedAnimation = TargetedAnimation;
  45764. /**
  45765. * Use this class to create coordinated animations on multiple targets
  45766. */
  45767. var AnimationGroup = /** @class */ (function () {
  45768. function AnimationGroup(name, scene) {
  45769. if (scene === void 0) { scene = null; }
  45770. this.name = name;
  45771. this._targetedAnimations = new Array();
  45772. this._animatables = new Array();
  45773. this._from = Number.MAX_VALUE;
  45774. this._to = -Number.MAX_VALUE;
  45775. this._speedRatio = 1;
  45776. this.onAnimationEndObservable = new BABYLON.Observable();
  45777. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  45778. this._scene.animationGroups.push(this);
  45779. }
  45780. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  45781. /**
  45782. * Define if the animations are started
  45783. */
  45784. get: function () {
  45785. return this._isStarted;
  45786. },
  45787. enumerable: true,
  45788. configurable: true
  45789. });
  45790. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  45791. /**
  45792. * Gets or sets the speed ratio to use for all animations
  45793. */
  45794. get: function () {
  45795. return this._speedRatio;
  45796. },
  45797. /**
  45798. * Gets or sets the speed ratio to use for all animations
  45799. */
  45800. set: function (value) {
  45801. if (this._speedRatio === value) {
  45802. return;
  45803. }
  45804. this._speedRatio = value;
  45805. for (var index = 0; index < this._animatables.length; index++) {
  45806. var animatable = this._animatables[index];
  45807. animatable.speedRatio = this._speedRatio;
  45808. }
  45809. },
  45810. enumerable: true,
  45811. configurable: true
  45812. });
  45813. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  45814. /**
  45815. * Gets the targeted animations for this animation group
  45816. */
  45817. get: function () {
  45818. return this._targetedAnimations;
  45819. },
  45820. enumerable: true,
  45821. configurable: true
  45822. });
  45823. /**
  45824. * Add an animation (with its target) in the group
  45825. * @param animation defines the animation we want to add
  45826. * @param target defines the target of the animation
  45827. * @returns the {BABYLON.TargetedAnimation} object
  45828. */
  45829. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  45830. var targetedAnimation = {
  45831. animation: animation,
  45832. target: target
  45833. };
  45834. var keys = animation.getKeys();
  45835. if (this._from > keys[0].frame) {
  45836. this._from = keys[0].frame;
  45837. }
  45838. if (this._to < keys[keys.length - 1].frame) {
  45839. this._to = keys[keys.length - 1].frame;
  45840. }
  45841. this._targetedAnimations.push(targetedAnimation);
  45842. return targetedAnimation;
  45843. };
  45844. /**
  45845. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  45846. * It can add constant keys at begin or end
  45847. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  45848. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  45849. */
  45850. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  45851. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  45852. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  45853. beginFrame = Math.max(beginFrame, this._from);
  45854. endFrame = Math.min(endFrame, this._to);
  45855. for (var index = 0; index < this._targetedAnimations.length; index++) {
  45856. var targetedAnimation = this._targetedAnimations[index];
  45857. var keys = targetedAnimation.animation.getKeys();
  45858. var startKey = keys[0];
  45859. var endKey = keys[keys.length - 1];
  45860. if (startKey.frame > beginFrame) {
  45861. var newKey = {
  45862. frame: beginFrame,
  45863. value: startKey.value,
  45864. inTangent: startKey.inTangent,
  45865. outTangent: startKey.outTangent,
  45866. interpolation: startKey.interpolation
  45867. };
  45868. keys.splice(0, 0, newKey);
  45869. }
  45870. if (endKey.frame < endFrame) {
  45871. var newKey = {
  45872. frame: endFrame,
  45873. value: endKey.value,
  45874. inTangent: endKey.outTangent,
  45875. outTangent: endKey.outTangent,
  45876. interpolation: endKey.interpolation
  45877. };
  45878. keys.push(newKey);
  45879. }
  45880. }
  45881. return this;
  45882. };
  45883. /**
  45884. * Start all animations on given targets
  45885. * @param loop defines if animations must loop
  45886. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  45887. */
  45888. AnimationGroup.prototype.start = function (loop, speedRatio) {
  45889. var _this = this;
  45890. if (loop === void 0) { loop = false; }
  45891. if (speedRatio === void 0) { speedRatio = 1; }
  45892. if (this._isStarted || this._targetedAnimations.length === 0) {
  45893. return this;
  45894. }
  45895. var _loop_1 = function () {
  45896. var targetedAnimation = this_1._targetedAnimations[index];
  45897. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  45898. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  45899. }));
  45900. };
  45901. var this_1 = this;
  45902. for (var index = 0; index < this._targetedAnimations.length; index++) {
  45903. _loop_1();
  45904. }
  45905. this._speedRatio = speedRatio;
  45906. this._isStarted = true;
  45907. return this;
  45908. };
  45909. /**
  45910. * Pause all animations
  45911. */
  45912. AnimationGroup.prototype.pause = function () {
  45913. if (!this._isStarted) {
  45914. return this;
  45915. }
  45916. for (var index = 0; index < this._animatables.length; index++) {
  45917. var animatable = this._animatables[index];
  45918. animatable.pause();
  45919. }
  45920. return this;
  45921. };
  45922. /**
  45923. * Play all animations to initial state
  45924. * This function will start() the animations if they were not started or will restart() them if they were paused
  45925. * @param loop defines if animations must loop
  45926. */
  45927. AnimationGroup.prototype.play = function (loop) {
  45928. if (this.isStarted) {
  45929. if (loop !== undefined) {
  45930. for (var index = 0; index < this._animatables.length; index++) {
  45931. var animatable = this._animatables[index];
  45932. animatable.loopAnimation = loop;
  45933. }
  45934. }
  45935. this.restart();
  45936. }
  45937. else {
  45938. this.start(loop, this._speedRatio);
  45939. }
  45940. return this;
  45941. };
  45942. /**
  45943. * Reset all animations to initial state
  45944. */
  45945. AnimationGroup.prototype.reset = function () {
  45946. if (!this._isStarted) {
  45947. return this;
  45948. }
  45949. for (var index = 0; index < this._animatables.length; index++) {
  45950. var animatable = this._animatables[index];
  45951. animatable.reset();
  45952. }
  45953. return this;
  45954. };
  45955. /**
  45956. * Restart animations from key 0
  45957. */
  45958. AnimationGroup.prototype.restart = function () {
  45959. if (!this._isStarted) {
  45960. return this;
  45961. }
  45962. for (var index = 0; index < this._animatables.length; index++) {
  45963. var animatable = this._animatables[index];
  45964. animatable.restart();
  45965. }
  45966. return this;
  45967. };
  45968. /**
  45969. * Stop all animations
  45970. */
  45971. AnimationGroup.prototype.stop = function () {
  45972. if (!this._isStarted) {
  45973. return this;
  45974. }
  45975. for (var index = 0; index < this._animatables.length; index++) {
  45976. var animatable = this._animatables[index];
  45977. animatable.stop();
  45978. }
  45979. this._isStarted = false;
  45980. return this;
  45981. };
  45982. /**
  45983. * Dispose all associated resources
  45984. */
  45985. AnimationGroup.prototype.dispose = function () {
  45986. this._targetedAnimations = [];
  45987. this._animatables = [];
  45988. var index = this._scene.animationGroups.indexOf(this);
  45989. if (index > -1) {
  45990. this._scene.animationGroups.splice(index, 1);
  45991. }
  45992. };
  45993. return AnimationGroup;
  45994. }());
  45995. BABYLON.AnimationGroup = AnimationGroup;
  45996. })(BABYLON || (BABYLON = {}));
  45997. //# sourceMappingURL=babylon.animationGroup.js.map
  45998. var BABYLON;
  45999. (function (BABYLON) {
  46000. var RuntimeAnimation = /** @class */ (function () {
  46001. function RuntimeAnimation(target, animation) {
  46002. this._offsetsCache = {};
  46003. this._highLimitsCache = {};
  46004. this._stopped = false;
  46005. this._blendingFactor = 0;
  46006. this._ratioOffset = 0;
  46007. this._animation = animation;
  46008. this._target = target;
  46009. animation._runtimeAnimations.push(this);
  46010. }
  46011. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  46012. get: function () {
  46013. return this._animation;
  46014. },
  46015. enumerable: true,
  46016. configurable: true
  46017. });
  46018. RuntimeAnimation.prototype.reset = function () {
  46019. this._offsetsCache = {};
  46020. this._highLimitsCache = {};
  46021. this.currentFrame = 0;
  46022. this._blendingFactor = 0;
  46023. this._originalBlendValue = null;
  46024. };
  46025. RuntimeAnimation.prototype.isStopped = function () {
  46026. return this._stopped;
  46027. };
  46028. RuntimeAnimation.prototype.dispose = function () {
  46029. var index = this._animation.runtimeAnimations.indexOf(this);
  46030. if (index > -1) {
  46031. this._animation.runtimeAnimations.splice(index, 1);
  46032. }
  46033. };
  46034. RuntimeAnimation.prototype._getKeyValue = function (value) {
  46035. if (typeof value === "function") {
  46036. return value();
  46037. }
  46038. return value;
  46039. };
  46040. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  46041. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  46042. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  46043. }
  46044. this.currentFrame = currentFrame;
  46045. var keys = this._animation.getKeys();
  46046. // Try to get a hash to find the right key
  46047. 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));
  46048. if (keys[startKeyIndex].frame >= currentFrame) {
  46049. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  46050. startKeyIndex--;
  46051. }
  46052. }
  46053. for (var key = startKeyIndex; key < keys.length; key++) {
  46054. var endKey = keys[key + 1];
  46055. if (endKey.frame >= currentFrame) {
  46056. var startKey = keys[key];
  46057. var startValue = this._getKeyValue(startKey.value);
  46058. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  46059. return startValue;
  46060. }
  46061. var endValue = this._getKeyValue(endKey.value);
  46062. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  46063. var frameDelta = endKey.frame - startKey.frame;
  46064. // gradient : percent of currentFrame between the frame inf and the frame sup
  46065. var gradient = (currentFrame - startKey.frame) / frameDelta;
  46066. // check for easingFunction and correction of gradient
  46067. var easingFunction = this._animation.getEasingFunction();
  46068. if (easingFunction != null) {
  46069. gradient = easingFunction.ease(gradient);
  46070. }
  46071. switch (this._animation.dataType) {
  46072. // Float
  46073. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46074. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  46075. switch (loopMode) {
  46076. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46077. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46078. return floatValue;
  46079. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46080. return offsetValue * repeatCount + floatValue;
  46081. }
  46082. break;
  46083. // Quaternion
  46084. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46085. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  46086. switch (loopMode) {
  46087. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46088. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46089. return quatValue;
  46090. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46091. return quatValue.add(offsetValue.scale(repeatCount));
  46092. }
  46093. return quatValue;
  46094. // Vector3
  46095. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46096. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  46097. switch (loopMode) {
  46098. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46099. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46100. return vec3Value;
  46101. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46102. return vec3Value.add(offsetValue.scale(repeatCount));
  46103. }
  46104. // Vector2
  46105. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46106. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  46107. switch (loopMode) {
  46108. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46109. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46110. return vec2Value;
  46111. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46112. return vec2Value.add(offsetValue.scale(repeatCount));
  46113. }
  46114. // Size
  46115. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46116. switch (loopMode) {
  46117. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46118. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46119. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  46120. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46121. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46122. }
  46123. // Color3
  46124. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46125. switch (loopMode) {
  46126. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46127. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46128. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  46129. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46130. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46131. }
  46132. // Matrix
  46133. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  46134. switch (loopMode) {
  46135. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46136. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46137. if (BABYLON.Animation.AllowMatricesInterpolation) {
  46138. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  46139. }
  46140. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46141. return startValue;
  46142. }
  46143. default:
  46144. break;
  46145. }
  46146. break;
  46147. }
  46148. }
  46149. return this._getKeyValue(keys[keys.length - 1].value);
  46150. };
  46151. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  46152. if (blend === void 0) { blend = false; }
  46153. // Set value
  46154. var path;
  46155. var destination;
  46156. var targetPropertyPath = this._animation.targetPropertyPath;
  46157. if (targetPropertyPath.length > 1) {
  46158. var property = this._target[targetPropertyPath[0]];
  46159. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  46160. property = property[targetPropertyPath[index]];
  46161. }
  46162. path = targetPropertyPath[targetPropertyPath.length - 1];
  46163. destination = property;
  46164. }
  46165. else {
  46166. path = targetPropertyPath[0];
  46167. destination = this._target;
  46168. }
  46169. // Blending
  46170. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  46171. if (!this._originalBlendValue) {
  46172. if (destination[path].clone) {
  46173. this._originalBlendValue = destination[path].clone();
  46174. }
  46175. else {
  46176. this._originalBlendValue = destination[path];
  46177. }
  46178. }
  46179. if (this._originalBlendValue.prototype) {
  46180. if (this._originalBlendValue.prototype.Lerp) {
  46181. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  46182. }
  46183. else {
  46184. destination[path] = currentValue;
  46185. }
  46186. }
  46187. else if (this._originalBlendValue.m) {
  46188. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  46189. }
  46190. else {
  46191. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  46192. }
  46193. this._blendingFactor += this._animation.blendingSpeed;
  46194. }
  46195. else {
  46196. destination[path] = currentValue;
  46197. }
  46198. if (this._target.markAsDirty) {
  46199. this._target.markAsDirty(this._animation.targetProperty);
  46200. }
  46201. };
  46202. RuntimeAnimation.prototype.goToFrame = function (frame) {
  46203. var keys = this._animation.getKeys();
  46204. if (frame < keys[0].frame) {
  46205. frame = keys[0].frame;
  46206. }
  46207. else if (frame > keys[keys.length - 1].frame) {
  46208. frame = keys[keys.length - 1].frame;
  46209. }
  46210. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  46211. this.setValue(currentValue);
  46212. };
  46213. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  46214. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  46215. this._ratioOffset = this._previousRatio - newRatio;
  46216. };
  46217. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  46218. if (blend === void 0) { blend = false; }
  46219. var targetPropertyPath = this._animation.targetPropertyPath;
  46220. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  46221. this._stopped = true;
  46222. return false;
  46223. }
  46224. var returnValue = true;
  46225. var keys = this._animation.getKeys();
  46226. // Adding a start key at frame 0 if missing
  46227. if (keys[0].frame !== 0) {
  46228. var newKey = { frame: 0, value: keys[0].value };
  46229. keys.splice(0, 0, newKey);
  46230. }
  46231. // Check limits
  46232. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  46233. from = keys[0].frame;
  46234. }
  46235. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  46236. to = keys[keys.length - 1].frame;
  46237. }
  46238. //to and from cannot be the same key
  46239. if (from === to) {
  46240. if (from > keys[0].frame) {
  46241. from--;
  46242. }
  46243. else if (to < keys[keys.length - 1].frame) {
  46244. to++;
  46245. }
  46246. }
  46247. // Compute ratio
  46248. var range = to - from;
  46249. var offsetValue;
  46250. // ratio represents the frame delta between from and to
  46251. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  46252. var highLimitValue = 0;
  46253. this._previousDelay = delay;
  46254. this._previousRatio = ratio;
  46255. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  46256. returnValue = false;
  46257. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  46258. }
  46259. else {
  46260. // Get max value if required
  46261. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  46262. var keyOffset = to.toString() + from.toString();
  46263. if (!this._offsetsCache[keyOffset]) {
  46264. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46265. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46266. switch (this._animation.dataType) {
  46267. // Float
  46268. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46269. this._offsetsCache[keyOffset] = toValue - fromValue;
  46270. break;
  46271. // Quaternion
  46272. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46273. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46274. break;
  46275. // Vector3
  46276. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46277. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46278. // Vector2
  46279. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46280. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46281. // Size
  46282. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46283. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46284. // Color3
  46285. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46286. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46287. default:
  46288. break;
  46289. }
  46290. this._highLimitsCache[keyOffset] = toValue;
  46291. }
  46292. highLimitValue = this._highLimitsCache[keyOffset];
  46293. offsetValue = this._offsetsCache[keyOffset];
  46294. }
  46295. }
  46296. if (offsetValue === undefined) {
  46297. switch (this._animation.dataType) {
  46298. // Float
  46299. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46300. offsetValue = 0;
  46301. break;
  46302. // Quaternion
  46303. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46304. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  46305. break;
  46306. // Vector3
  46307. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46308. offsetValue = BABYLON.Vector3.Zero();
  46309. break;
  46310. // Vector2
  46311. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46312. offsetValue = BABYLON.Vector2.Zero();
  46313. break;
  46314. // Size
  46315. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46316. offsetValue = BABYLON.Size.Zero();
  46317. break;
  46318. // Color3
  46319. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46320. offsetValue = BABYLON.Color3.Black();
  46321. }
  46322. }
  46323. // Compute value
  46324. var repeatCount = (ratio / range) >> 0;
  46325. var currentFrame = returnValue ? from + ratio % range : to;
  46326. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  46327. // Set value
  46328. this.setValue(currentValue);
  46329. // Check events
  46330. var events = this._animation.getEvents();
  46331. for (var index = 0; index < events.length; index++) {
  46332. // Make sure current frame has passed event frame and that event frame is within the current range
  46333. // Also, handle both forward and reverse animations
  46334. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  46335. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  46336. var event = events[index];
  46337. if (!event.isDone) {
  46338. // If event should be done only once, remove it.
  46339. if (event.onlyOnce) {
  46340. events.splice(index, 1);
  46341. index--;
  46342. }
  46343. event.isDone = true;
  46344. event.action();
  46345. } // Don't do anything if the event has already be done.
  46346. }
  46347. else if (events[index].isDone && !events[index].onlyOnce) {
  46348. // reset event, the animation is looping
  46349. events[index].isDone = false;
  46350. }
  46351. }
  46352. if (!returnValue) {
  46353. this._stopped = true;
  46354. }
  46355. return returnValue;
  46356. };
  46357. return RuntimeAnimation;
  46358. }());
  46359. BABYLON.RuntimeAnimation = RuntimeAnimation;
  46360. })(BABYLON || (BABYLON = {}));
  46361. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  46362. var BABYLON;
  46363. (function (BABYLON) {
  46364. var Animatable = /** @class */ (function () {
  46365. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  46366. if (fromFrame === void 0) { fromFrame = 0; }
  46367. if (toFrame === void 0) { toFrame = 100; }
  46368. if (loopAnimation === void 0) { loopAnimation = false; }
  46369. if (speedRatio === void 0) { speedRatio = 1.0; }
  46370. this.target = target;
  46371. this.fromFrame = fromFrame;
  46372. this.toFrame = toFrame;
  46373. this.loopAnimation = loopAnimation;
  46374. this.onAnimationEnd = onAnimationEnd;
  46375. this._localDelayOffset = null;
  46376. this._pausedDelay = null;
  46377. this._runtimeAnimations = new Array();
  46378. this._paused = false;
  46379. this._speedRatio = 1;
  46380. this.animationStarted = false;
  46381. if (animations) {
  46382. this.appendAnimations(target, animations);
  46383. }
  46384. this._speedRatio = speedRatio;
  46385. this._scene = scene;
  46386. scene._activeAnimatables.push(this);
  46387. }
  46388. Object.defineProperty(Animatable.prototype, "speedRatio", {
  46389. get: function () {
  46390. return this._speedRatio;
  46391. },
  46392. set: function (value) {
  46393. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  46394. var animation = this._runtimeAnimations[index];
  46395. animation._prepareForSpeedRatioChange(value);
  46396. }
  46397. this._speedRatio = value;
  46398. },
  46399. enumerable: true,
  46400. configurable: true
  46401. });
  46402. // Methods
  46403. Animatable.prototype.getAnimations = function () {
  46404. return this._runtimeAnimations;
  46405. };
  46406. Animatable.prototype.appendAnimations = function (target, animations) {
  46407. for (var index = 0; index < animations.length; index++) {
  46408. var animation = animations[index];
  46409. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  46410. }
  46411. };
  46412. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  46413. var runtimeAnimations = this._runtimeAnimations;
  46414. for (var index = 0; index < runtimeAnimations.length; index++) {
  46415. if (runtimeAnimations[index].animation.targetProperty === property) {
  46416. return runtimeAnimations[index].animation;
  46417. }
  46418. }
  46419. return null;
  46420. };
  46421. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  46422. var runtimeAnimations = this._runtimeAnimations;
  46423. for (var index = 0; index < runtimeAnimations.length; index++) {
  46424. if (runtimeAnimations[index].animation.targetProperty === property) {
  46425. return runtimeAnimations[index];
  46426. }
  46427. }
  46428. return null;
  46429. };
  46430. Animatable.prototype.reset = function () {
  46431. var runtimeAnimations = this._runtimeAnimations;
  46432. for (var index = 0; index < runtimeAnimations.length; index++) {
  46433. runtimeAnimations[index].reset();
  46434. }
  46435. // Reset to original value
  46436. for (index = 0; index < runtimeAnimations.length; index++) {
  46437. var animation = runtimeAnimations[index];
  46438. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  46439. }
  46440. this._localDelayOffset = null;
  46441. this._pausedDelay = null;
  46442. };
  46443. Animatable.prototype.enableBlending = function (blendingSpeed) {
  46444. var runtimeAnimations = this._runtimeAnimations;
  46445. for (var index = 0; index < runtimeAnimations.length; index++) {
  46446. runtimeAnimations[index].animation.enableBlending = true;
  46447. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  46448. }
  46449. };
  46450. Animatable.prototype.disableBlending = function () {
  46451. var runtimeAnimations = this._runtimeAnimations;
  46452. for (var index = 0; index < runtimeAnimations.length; index++) {
  46453. runtimeAnimations[index].animation.enableBlending = false;
  46454. }
  46455. };
  46456. Animatable.prototype.goToFrame = function (frame) {
  46457. var runtimeAnimations = this._runtimeAnimations;
  46458. if (runtimeAnimations[0]) {
  46459. var fps = runtimeAnimations[0].animation.framePerSecond;
  46460. var currentFrame = runtimeAnimations[0].currentFrame;
  46461. var adjustTime = frame - currentFrame;
  46462. var delay = adjustTime * 1000 / fps;
  46463. if (this._localDelayOffset === null) {
  46464. this._localDelayOffset = 0;
  46465. }
  46466. this._localDelayOffset -= delay;
  46467. }
  46468. for (var index = 0; index < runtimeAnimations.length; index++) {
  46469. runtimeAnimations[index].goToFrame(frame);
  46470. }
  46471. };
  46472. Animatable.prototype.pause = function () {
  46473. if (this._paused) {
  46474. return;
  46475. }
  46476. this._paused = true;
  46477. };
  46478. Animatable.prototype.restart = function () {
  46479. this._paused = false;
  46480. };
  46481. Animatable.prototype.stop = function (animationName) {
  46482. if (animationName) {
  46483. var idx = this._scene._activeAnimatables.indexOf(this);
  46484. if (idx > -1) {
  46485. var runtimeAnimations = this._runtimeAnimations;
  46486. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  46487. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  46488. continue;
  46489. }
  46490. runtimeAnimations[index].dispose();
  46491. runtimeAnimations.splice(index, 1);
  46492. }
  46493. if (runtimeAnimations.length == 0) {
  46494. this._scene._activeAnimatables.splice(idx, 1);
  46495. if (this.onAnimationEnd) {
  46496. this.onAnimationEnd();
  46497. }
  46498. }
  46499. }
  46500. }
  46501. else {
  46502. var index = this._scene._activeAnimatables.indexOf(this);
  46503. if (index > -1) {
  46504. this._scene._activeAnimatables.splice(index, 1);
  46505. var runtimeAnimations = this._runtimeAnimations;
  46506. for (var index = 0; index < runtimeAnimations.length; index++) {
  46507. runtimeAnimations[index].dispose();
  46508. }
  46509. if (this.onAnimationEnd) {
  46510. this.onAnimationEnd();
  46511. }
  46512. }
  46513. }
  46514. };
  46515. Animatable.prototype._animate = function (delay) {
  46516. if (this._paused) {
  46517. this.animationStarted = false;
  46518. if (this._pausedDelay === null) {
  46519. this._pausedDelay = delay;
  46520. }
  46521. return true;
  46522. }
  46523. if (this._localDelayOffset === null) {
  46524. this._localDelayOffset = delay;
  46525. this._pausedDelay = null;
  46526. }
  46527. else if (this._pausedDelay !== null) {
  46528. this._localDelayOffset += delay - this._pausedDelay;
  46529. this._pausedDelay = null;
  46530. }
  46531. // Animating
  46532. var running = false;
  46533. var runtimeAnimations = this._runtimeAnimations;
  46534. var index;
  46535. for (index = 0; index < runtimeAnimations.length; index++) {
  46536. var animation = runtimeAnimations[index];
  46537. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  46538. running = running || isRunning;
  46539. }
  46540. this.animationStarted = running;
  46541. if (!running) {
  46542. // Remove from active animatables
  46543. index = this._scene._activeAnimatables.indexOf(this);
  46544. this._scene._activeAnimatables.splice(index, 1);
  46545. // Dispose all runtime animations
  46546. for (index = 0; index < runtimeAnimations.length; index++) {
  46547. runtimeAnimations[index].dispose();
  46548. }
  46549. }
  46550. if (!running && this.onAnimationEnd) {
  46551. this.onAnimationEnd();
  46552. this.onAnimationEnd = null;
  46553. }
  46554. return running;
  46555. };
  46556. return Animatable;
  46557. }());
  46558. BABYLON.Animatable = Animatable;
  46559. })(BABYLON || (BABYLON = {}));
  46560. //# sourceMappingURL=babylon.animatable.js.map
  46561. var BABYLON;
  46562. (function (BABYLON) {
  46563. var EasingFunction = /** @class */ (function () {
  46564. function EasingFunction() {
  46565. // Properties
  46566. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  46567. }
  46568. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  46569. get: function () {
  46570. return EasingFunction._EASINGMODE_EASEIN;
  46571. },
  46572. enumerable: true,
  46573. configurable: true
  46574. });
  46575. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  46576. get: function () {
  46577. return EasingFunction._EASINGMODE_EASEOUT;
  46578. },
  46579. enumerable: true,
  46580. configurable: true
  46581. });
  46582. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  46583. get: function () {
  46584. return EasingFunction._EASINGMODE_EASEINOUT;
  46585. },
  46586. enumerable: true,
  46587. configurable: true
  46588. });
  46589. EasingFunction.prototype.setEasingMode = function (easingMode) {
  46590. var n = Math.min(Math.max(easingMode, 0), 2);
  46591. this._easingMode = n;
  46592. };
  46593. EasingFunction.prototype.getEasingMode = function () {
  46594. return this._easingMode;
  46595. };
  46596. EasingFunction.prototype.easeInCore = function (gradient) {
  46597. throw new Error('You must implement this method');
  46598. };
  46599. EasingFunction.prototype.ease = function (gradient) {
  46600. switch (this._easingMode) {
  46601. case EasingFunction.EASINGMODE_EASEIN:
  46602. return this.easeInCore(gradient);
  46603. case EasingFunction.EASINGMODE_EASEOUT:
  46604. return (1 - this.easeInCore(1 - gradient));
  46605. }
  46606. if (gradient >= 0.5) {
  46607. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  46608. }
  46609. return (this.easeInCore(gradient * 2) * 0.5);
  46610. };
  46611. //Statics
  46612. EasingFunction._EASINGMODE_EASEIN = 0;
  46613. EasingFunction._EASINGMODE_EASEOUT = 1;
  46614. EasingFunction._EASINGMODE_EASEINOUT = 2;
  46615. return EasingFunction;
  46616. }());
  46617. BABYLON.EasingFunction = EasingFunction;
  46618. var CircleEase = /** @class */ (function (_super) {
  46619. __extends(CircleEase, _super);
  46620. function CircleEase() {
  46621. return _super !== null && _super.apply(this, arguments) || this;
  46622. }
  46623. CircleEase.prototype.easeInCore = function (gradient) {
  46624. gradient = Math.max(0, Math.min(1, gradient));
  46625. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  46626. };
  46627. return CircleEase;
  46628. }(EasingFunction));
  46629. BABYLON.CircleEase = CircleEase;
  46630. var BackEase = /** @class */ (function (_super) {
  46631. __extends(BackEase, _super);
  46632. function BackEase(amplitude) {
  46633. if (amplitude === void 0) { amplitude = 1; }
  46634. var _this = _super.call(this) || this;
  46635. _this.amplitude = amplitude;
  46636. return _this;
  46637. }
  46638. BackEase.prototype.easeInCore = function (gradient) {
  46639. var num = Math.max(0, this.amplitude);
  46640. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  46641. };
  46642. return BackEase;
  46643. }(EasingFunction));
  46644. BABYLON.BackEase = BackEase;
  46645. var BounceEase = /** @class */ (function (_super) {
  46646. __extends(BounceEase, _super);
  46647. function BounceEase(bounces, bounciness) {
  46648. if (bounces === void 0) { bounces = 3; }
  46649. if (bounciness === void 0) { bounciness = 2; }
  46650. var _this = _super.call(this) || this;
  46651. _this.bounces = bounces;
  46652. _this.bounciness = bounciness;
  46653. return _this;
  46654. }
  46655. BounceEase.prototype.easeInCore = function (gradient) {
  46656. var y = Math.max(0.0, this.bounces);
  46657. var bounciness = this.bounciness;
  46658. if (bounciness <= 1.0) {
  46659. bounciness = 1.001;
  46660. }
  46661. var num9 = Math.pow(bounciness, y);
  46662. var num5 = 1.0 - bounciness;
  46663. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  46664. var num15 = gradient * num4;
  46665. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  46666. var num3 = Math.floor(num65);
  46667. var num13 = num3 + 1.0;
  46668. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  46669. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  46670. var num7 = (num8 + num12) * 0.5;
  46671. var num6 = gradient - num7;
  46672. var num2 = num7 - num8;
  46673. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  46674. };
  46675. return BounceEase;
  46676. }(EasingFunction));
  46677. BABYLON.BounceEase = BounceEase;
  46678. var CubicEase = /** @class */ (function (_super) {
  46679. __extends(CubicEase, _super);
  46680. function CubicEase() {
  46681. return _super !== null && _super.apply(this, arguments) || this;
  46682. }
  46683. CubicEase.prototype.easeInCore = function (gradient) {
  46684. return (gradient * gradient * gradient);
  46685. };
  46686. return CubicEase;
  46687. }(EasingFunction));
  46688. BABYLON.CubicEase = CubicEase;
  46689. var ElasticEase = /** @class */ (function (_super) {
  46690. __extends(ElasticEase, _super);
  46691. function ElasticEase(oscillations, springiness) {
  46692. if (oscillations === void 0) { oscillations = 3; }
  46693. if (springiness === void 0) { springiness = 3; }
  46694. var _this = _super.call(this) || this;
  46695. _this.oscillations = oscillations;
  46696. _this.springiness = springiness;
  46697. return _this;
  46698. }
  46699. ElasticEase.prototype.easeInCore = function (gradient) {
  46700. var num2;
  46701. var num3 = Math.max(0.0, this.oscillations);
  46702. var num = Math.max(0.0, this.springiness);
  46703. if (num == 0) {
  46704. num2 = gradient;
  46705. }
  46706. else {
  46707. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  46708. }
  46709. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  46710. };
  46711. return ElasticEase;
  46712. }(EasingFunction));
  46713. BABYLON.ElasticEase = ElasticEase;
  46714. var ExponentialEase = /** @class */ (function (_super) {
  46715. __extends(ExponentialEase, _super);
  46716. function ExponentialEase(exponent) {
  46717. if (exponent === void 0) { exponent = 2; }
  46718. var _this = _super.call(this) || this;
  46719. _this.exponent = exponent;
  46720. return _this;
  46721. }
  46722. ExponentialEase.prototype.easeInCore = function (gradient) {
  46723. if (this.exponent <= 0) {
  46724. return gradient;
  46725. }
  46726. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  46727. };
  46728. return ExponentialEase;
  46729. }(EasingFunction));
  46730. BABYLON.ExponentialEase = ExponentialEase;
  46731. var PowerEase = /** @class */ (function (_super) {
  46732. __extends(PowerEase, _super);
  46733. function PowerEase(power) {
  46734. if (power === void 0) { power = 2; }
  46735. var _this = _super.call(this) || this;
  46736. _this.power = power;
  46737. return _this;
  46738. }
  46739. PowerEase.prototype.easeInCore = function (gradient) {
  46740. var y = Math.max(0.0, this.power);
  46741. return Math.pow(gradient, y);
  46742. };
  46743. return PowerEase;
  46744. }(EasingFunction));
  46745. BABYLON.PowerEase = PowerEase;
  46746. var QuadraticEase = /** @class */ (function (_super) {
  46747. __extends(QuadraticEase, _super);
  46748. function QuadraticEase() {
  46749. return _super !== null && _super.apply(this, arguments) || this;
  46750. }
  46751. QuadraticEase.prototype.easeInCore = function (gradient) {
  46752. return (gradient * gradient);
  46753. };
  46754. return QuadraticEase;
  46755. }(EasingFunction));
  46756. BABYLON.QuadraticEase = QuadraticEase;
  46757. var QuarticEase = /** @class */ (function (_super) {
  46758. __extends(QuarticEase, _super);
  46759. function QuarticEase() {
  46760. return _super !== null && _super.apply(this, arguments) || this;
  46761. }
  46762. QuarticEase.prototype.easeInCore = function (gradient) {
  46763. return (gradient * gradient * gradient * gradient);
  46764. };
  46765. return QuarticEase;
  46766. }(EasingFunction));
  46767. BABYLON.QuarticEase = QuarticEase;
  46768. var QuinticEase = /** @class */ (function (_super) {
  46769. __extends(QuinticEase, _super);
  46770. function QuinticEase() {
  46771. return _super !== null && _super.apply(this, arguments) || this;
  46772. }
  46773. QuinticEase.prototype.easeInCore = function (gradient) {
  46774. return (gradient * gradient * gradient * gradient * gradient);
  46775. };
  46776. return QuinticEase;
  46777. }(EasingFunction));
  46778. BABYLON.QuinticEase = QuinticEase;
  46779. var SineEase = /** @class */ (function (_super) {
  46780. __extends(SineEase, _super);
  46781. function SineEase() {
  46782. return _super !== null && _super.apply(this, arguments) || this;
  46783. }
  46784. SineEase.prototype.easeInCore = function (gradient) {
  46785. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  46786. };
  46787. return SineEase;
  46788. }(EasingFunction));
  46789. BABYLON.SineEase = SineEase;
  46790. var BezierCurveEase = /** @class */ (function (_super) {
  46791. __extends(BezierCurveEase, _super);
  46792. function BezierCurveEase(x1, y1, x2, y2) {
  46793. if (x1 === void 0) { x1 = 0; }
  46794. if (y1 === void 0) { y1 = 0; }
  46795. if (x2 === void 0) { x2 = 1; }
  46796. if (y2 === void 0) { y2 = 1; }
  46797. var _this = _super.call(this) || this;
  46798. _this.x1 = x1;
  46799. _this.y1 = y1;
  46800. _this.x2 = x2;
  46801. _this.y2 = y2;
  46802. return _this;
  46803. }
  46804. BezierCurveEase.prototype.easeInCore = function (gradient) {
  46805. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  46806. };
  46807. return BezierCurveEase;
  46808. }(EasingFunction));
  46809. BABYLON.BezierCurveEase = BezierCurveEase;
  46810. })(BABYLON || (BABYLON = {}));
  46811. //# sourceMappingURL=babylon.easing.js.map
  46812. var BABYLON;
  46813. (function (BABYLON) {
  46814. var Condition = /** @class */ (function () {
  46815. function Condition(actionManager) {
  46816. this._actionManager = actionManager;
  46817. }
  46818. Condition.prototype.isValid = function () {
  46819. return true;
  46820. };
  46821. Condition.prototype._getProperty = function (propertyPath) {
  46822. return this._actionManager._getProperty(propertyPath);
  46823. };
  46824. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  46825. return this._actionManager._getEffectiveTarget(target, propertyPath);
  46826. };
  46827. Condition.prototype.serialize = function () {
  46828. };
  46829. Condition.prototype._serialize = function (serializedCondition) {
  46830. return {
  46831. type: 2,
  46832. children: [],
  46833. name: serializedCondition.name,
  46834. properties: serializedCondition.properties
  46835. };
  46836. };
  46837. return Condition;
  46838. }());
  46839. BABYLON.Condition = Condition;
  46840. var ValueCondition = /** @class */ (function (_super) {
  46841. __extends(ValueCondition, _super);
  46842. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  46843. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  46844. var _this = _super.call(this, actionManager) || this;
  46845. _this.propertyPath = propertyPath;
  46846. _this.value = value;
  46847. _this.operator = operator;
  46848. _this._target = target;
  46849. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  46850. _this._property = _this._getProperty(_this.propertyPath);
  46851. return _this;
  46852. }
  46853. Object.defineProperty(ValueCondition, "IsEqual", {
  46854. get: function () {
  46855. return ValueCondition._IsEqual;
  46856. },
  46857. enumerable: true,
  46858. configurable: true
  46859. });
  46860. Object.defineProperty(ValueCondition, "IsDifferent", {
  46861. get: function () {
  46862. return ValueCondition._IsDifferent;
  46863. },
  46864. enumerable: true,
  46865. configurable: true
  46866. });
  46867. Object.defineProperty(ValueCondition, "IsGreater", {
  46868. get: function () {
  46869. return ValueCondition._IsGreater;
  46870. },
  46871. enumerable: true,
  46872. configurable: true
  46873. });
  46874. Object.defineProperty(ValueCondition, "IsLesser", {
  46875. get: function () {
  46876. return ValueCondition._IsLesser;
  46877. },
  46878. enumerable: true,
  46879. configurable: true
  46880. });
  46881. // Methods
  46882. ValueCondition.prototype.isValid = function () {
  46883. switch (this.operator) {
  46884. case ValueCondition.IsGreater:
  46885. return this._effectiveTarget[this._property] > this.value;
  46886. case ValueCondition.IsLesser:
  46887. return this._effectiveTarget[this._property] < this.value;
  46888. case ValueCondition.IsEqual:
  46889. case ValueCondition.IsDifferent:
  46890. var check;
  46891. if (this.value.equals) {
  46892. check = this.value.equals(this._effectiveTarget[this._property]);
  46893. }
  46894. else {
  46895. check = this.value === this._effectiveTarget[this._property];
  46896. }
  46897. return this.operator === ValueCondition.IsEqual ? check : !check;
  46898. }
  46899. return false;
  46900. };
  46901. ValueCondition.prototype.serialize = function () {
  46902. return this._serialize({
  46903. name: "ValueCondition",
  46904. properties: [
  46905. BABYLON.Action._GetTargetProperty(this._target),
  46906. { name: "propertyPath", value: this.propertyPath },
  46907. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  46908. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  46909. ]
  46910. });
  46911. };
  46912. ValueCondition.GetOperatorName = function (operator) {
  46913. switch (operator) {
  46914. case ValueCondition._IsEqual: return "IsEqual";
  46915. case ValueCondition._IsDifferent: return "IsDifferent";
  46916. case ValueCondition._IsGreater: return "IsGreater";
  46917. case ValueCondition._IsLesser: return "IsLesser";
  46918. default: return "";
  46919. }
  46920. };
  46921. // Statics
  46922. ValueCondition._IsEqual = 0;
  46923. ValueCondition._IsDifferent = 1;
  46924. ValueCondition._IsGreater = 2;
  46925. ValueCondition._IsLesser = 3;
  46926. return ValueCondition;
  46927. }(Condition));
  46928. BABYLON.ValueCondition = ValueCondition;
  46929. var PredicateCondition = /** @class */ (function (_super) {
  46930. __extends(PredicateCondition, _super);
  46931. function PredicateCondition(actionManager, predicate) {
  46932. var _this = _super.call(this, actionManager) || this;
  46933. _this.predicate = predicate;
  46934. return _this;
  46935. }
  46936. PredicateCondition.prototype.isValid = function () {
  46937. return this.predicate();
  46938. };
  46939. return PredicateCondition;
  46940. }(Condition));
  46941. BABYLON.PredicateCondition = PredicateCondition;
  46942. var StateCondition = /** @class */ (function (_super) {
  46943. __extends(StateCondition, _super);
  46944. function StateCondition(actionManager, target, value) {
  46945. var _this = _super.call(this, actionManager) || this;
  46946. _this.value = value;
  46947. _this._target = target;
  46948. return _this;
  46949. }
  46950. // Methods
  46951. StateCondition.prototype.isValid = function () {
  46952. return this._target.state === this.value;
  46953. };
  46954. StateCondition.prototype.serialize = function () {
  46955. return this._serialize({
  46956. name: "StateCondition",
  46957. properties: [
  46958. BABYLON.Action._GetTargetProperty(this._target),
  46959. { name: "value", value: this.value }
  46960. ]
  46961. });
  46962. };
  46963. return StateCondition;
  46964. }(Condition));
  46965. BABYLON.StateCondition = StateCondition;
  46966. })(BABYLON || (BABYLON = {}));
  46967. //# sourceMappingURL=babylon.condition.js.map
  46968. var BABYLON;
  46969. (function (BABYLON) {
  46970. var Action = /** @class */ (function () {
  46971. function Action(triggerOptions, condition) {
  46972. this.triggerOptions = triggerOptions;
  46973. this.onBeforeExecuteObservable = new BABYLON.Observable();
  46974. if (triggerOptions.parameter) {
  46975. this.trigger = triggerOptions.trigger;
  46976. this._triggerParameter = triggerOptions.parameter;
  46977. }
  46978. else {
  46979. this.trigger = triggerOptions;
  46980. }
  46981. this._nextActiveAction = this;
  46982. this._condition = condition;
  46983. }
  46984. // Methods
  46985. Action.prototype._prepare = function () {
  46986. };
  46987. Action.prototype.getTriggerParameter = function () {
  46988. return this._triggerParameter;
  46989. };
  46990. Action.prototype._executeCurrent = function (evt) {
  46991. if (this._nextActiveAction._condition) {
  46992. var condition = this._nextActiveAction._condition;
  46993. var currentRenderId = this._actionManager.getScene().getRenderId();
  46994. // We cache the current evaluation for the current frame
  46995. if (condition._evaluationId === currentRenderId) {
  46996. if (!condition._currentResult) {
  46997. return;
  46998. }
  46999. }
  47000. else {
  47001. condition._evaluationId = currentRenderId;
  47002. if (!condition.isValid()) {
  47003. condition._currentResult = false;
  47004. return;
  47005. }
  47006. condition._currentResult = true;
  47007. }
  47008. }
  47009. this.onBeforeExecuteObservable.notifyObservers(this);
  47010. this._nextActiveAction.execute(evt);
  47011. this.skipToNextActiveAction();
  47012. };
  47013. Action.prototype.execute = function (evt) {
  47014. };
  47015. Action.prototype.skipToNextActiveAction = function () {
  47016. if (this._nextActiveAction._child) {
  47017. if (!this._nextActiveAction._child._actionManager) {
  47018. this._nextActiveAction._child._actionManager = this._actionManager;
  47019. }
  47020. this._nextActiveAction = this._nextActiveAction._child;
  47021. }
  47022. else {
  47023. this._nextActiveAction = this;
  47024. }
  47025. };
  47026. Action.prototype.then = function (action) {
  47027. this._child = action;
  47028. action._actionManager = this._actionManager;
  47029. action._prepare();
  47030. return action;
  47031. };
  47032. Action.prototype._getProperty = function (propertyPath) {
  47033. return this._actionManager._getProperty(propertyPath);
  47034. };
  47035. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  47036. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47037. };
  47038. Action.prototype.serialize = function (parent) {
  47039. };
  47040. // Called by BABYLON.Action objects in serialize(...). Internal use
  47041. Action.prototype._serialize = function (serializedAction, parent) {
  47042. var serializationObject = {
  47043. type: 1,
  47044. children: [],
  47045. name: serializedAction.name,
  47046. properties: serializedAction.properties || []
  47047. };
  47048. // Serialize child
  47049. if (this._child) {
  47050. this._child.serialize(serializationObject);
  47051. }
  47052. // Check if "this" has a condition
  47053. if (this._condition) {
  47054. var serializedCondition = this._condition.serialize();
  47055. serializedCondition.children.push(serializationObject);
  47056. if (parent) {
  47057. parent.children.push(serializedCondition);
  47058. }
  47059. return serializedCondition;
  47060. }
  47061. if (parent) {
  47062. parent.children.push(serializationObject);
  47063. }
  47064. return serializationObject;
  47065. };
  47066. Action._SerializeValueAsString = function (value) {
  47067. if (typeof value === "number") {
  47068. return value.toString();
  47069. }
  47070. if (typeof value === "boolean") {
  47071. return value ? "true" : "false";
  47072. }
  47073. if (value instanceof BABYLON.Vector2) {
  47074. return value.x + ", " + value.y;
  47075. }
  47076. if (value instanceof BABYLON.Vector3) {
  47077. return value.x + ", " + value.y + ", " + value.z;
  47078. }
  47079. if (value instanceof BABYLON.Color3) {
  47080. return value.r + ", " + value.g + ", " + value.b;
  47081. }
  47082. if (value instanceof BABYLON.Color4) {
  47083. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  47084. }
  47085. return value; // string
  47086. };
  47087. Action._GetTargetProperty = function (target) {
  47088. return {
  47089. name: "target",
  47090. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  47091. : target instanceof BABYLON.Light ? "LightProperties"
  47092. : target instanceof BABYLON.Camera ? "CameraProperties"
  47093. : "SceneProperties",
  47094. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  47095. };
  47096. };
  47097. return Action;
  47098. }());
  47099. BABYLON.Action = Action;
  47100. })(BABYLON || (BABYLON = {}));
  47101. //# sourceMappingURL=babylon.action.js.map
  47102. var BABYLON;
  47103. (function (BABYLON) {
  47104. /**
  47105. * ActionEvent is the event beint sent when an action is triggered.
  47106. */
  47107. var ActionEvent = /** @class */ (function () {
  47108. /**
  47109. * @param source The mesh or sprite that triggered the action.
  47110. * @param pointerX The X mouse cursor position at the time of the event
  47111. * @param pointerY The Y mouse cursor position at the time of the event
  47112. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  47113. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  47114. */
  47115. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  47116. this.source = source;
  47117. this.pointerX = pointerX;
  47118. this.pointerY = pointerY;
  47119. this.meshUnderPointer = meshUnderPointer;
  47120. this.sourceEvent = sourceEvent;
  47121. this.additionalData = additionalData;
  47122. }
  47123. /**
  47124. * Helper function to auto-create an ActionEvent from a source mesh.
  47125. * @param source The source mesh that triggered the event
  47126. * @param evt {Event} The original (browser) event
  47127. */
  47128. ActionEvent.CreateNew = function (source, evt, additionalData) {
  47129. var scene = source.getScene();
  47130. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47131. };
  47132. /**
  47133. * Helper function to auto-create an ActionEvent from a source mesh.
  47134. * @param source The source sprite that triggered the event
  47135. * @param scene Scene associated with the sprite
  47136. * @param evt {Event} The original (browser) event
  47137. */
  47138. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  47139. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47140. };
  47141. /**
  47142. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  47143. * @param scene the scene where the event occurred
  47144. * @param evt {Event} The original (browser) event
  47145. */
  47146. ActionEvent.CreateNewFromScene = function (scene, evt) {
  47147. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  47148. };
  47149. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  47150. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  47151. };
  47152. return ActionEvent;
  47153. }());
  47154. BABYLON.ActionEvent = ActionEvent;
  47155. /**
  47156. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  47157. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  47158. */
  47159. var ActionManager = /** @class */ (function () {
  47160. function ActionManager(scene) {
  47161. // Members
  47162. this.actions = new Array();
  47163. this.hoverCursor = '';
  47164. this._scene = scene;
  47165. scene._actionManagers.push(this);
  47166. }
  47167. Object.defineProperty(ActionManager, "NothingTrigger", {
  47168. get: function () {
  47169. return ActionManager._NothingTrigger;
  47170. },
  47171. enumerable: true,
  47172. configurable: true
  47173. });
  47174. Object.defineProperty(ActionManager, "OnPickTrigger", {
  47175. get: function () {
  47176. return ActionManager._OnPickTrigger;
  47177. },
  47178. enumerable: true,
  47179. configurable: true
  47180. });
  47181. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  47182. get: function () {
  47183. return ActionManager._OnLeftPickTrigger;
  47184. },
  47185. enumerable: true,
  47186. configurable: true
  47187. });
  47188. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  47189. get: function () {
  47190. return ActionManager._OnRightPickTrigger;
  47191. },
  47192. enumerable: true,
  47193. configurable: true
  47194. });
  47195. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  47196. get: function () {
  47197. return ActionManager._OnCenterPickTrigger;
  47198. },
  47199. enumerable: true,
  47200. configurable: true
  47201. });
  47202. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  47203. get: function () {
  47204. return ActionManager._OnPickDownTrigger;
  47205. },
  47206. enumerable: true,
  47207. configurable: true
  47208. });
  47209. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  47210. get: function () {
  47211. return ActionManager._OnDoublePickTrigger;
  47212. },
  47213. enumerable: true,
  47214. configurable: true
  47215. });
  47216. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  47217. get: function () {
  47218. return ActionManager._OnPickUpTrigger;
  47219. },
  47220. enumerable: true,
  47221. configurable: true
  47222. });
  47223. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  47224. /// This trigger will only be raised if you also declared a OnPickDown
  47225. get: function () {
  47226. return ActionManager._OnPickOutTrigger;
  47227. },
  47228. enumerable: true,
  47229. configurable: true
  47230. });
  47231. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  47232. get: function () {
  47233. return ActionManager._OnLongPressTrigger;
  47234. },
  47235. enumerable: true,
  47236. configurable: true
  47237. });
  47238. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  47239. get: function () {
  47240. return ActionManager._OnPointerOverTrigger;
  47241. },
  47242. enumerable: true,
  47243. configurable: true
  47244. });
  47245. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  47246. get: function () {
  47247. return ActionManager._OnPointerOutTrigger;
  47248. },
  47249. enumerable: true,
  47250. configurable: true
  47251. });
  47252. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  47253. get: function () {
  47254. return ActionManager._OnEveryFrameTrigger;
  47255. },
  47256. enumerable: true,
  47257. configurable: true
  47258. });
  47259. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  47260. get: function () {
  47261. return ActionManager._OnIntersectionEnterTrigger;
  47262. },
  47263. enumerable: true,
  47264. configurable: true
  47265. });
  47266. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  47267. get: function () {
  47268. return ActionManager._OnIntersectionExitTrigger;
  47269. },
  47270. enumerable: true,
  47271. configurable: true
  47272. });
  47273. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  47274. get: function () {
  47275. return ActionManager._OnKeyDownTrigger;
  47276. },
  47277. enumerable: true,
  47278. configurable: true
  47279. });
  47280. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  47281. get: function () {
  47282. return ActionManager._OnKeyUpTrigger;
  47283. },
  47284. enumerable: true,
  47285. configurable: true
  47286. });
  47287. // Methods
  47288. ActionManager.prototype.dispose = function () {
  47289. var index = this._scene._actionManagers.indexOf(this);
  47290. for (var i = 0; i < this.actions.length; i++) {
  47291. var action = this.actions[i];
  47292. ActionManager.Triggers[action.trigger]--;
  47293. if (ActionManager.Triggers[action.trigger] === 0) {
  47294. delete ActionManager.Triggers[action.trigger];
  47295. }
  47296. }
  47297. if (index > -1) {
  47298. this._scene._actionManagers.splice(index, 1);
  47299. }
  47300. };
  47301. ActionManager.prototype.getScene = function () {
  47302. return this._scene;
  47303. };
  47304. /**
  47305. * Does this action manager handles actions of any of the given triggers
  47306. * @param {number[]} triggers - the triggers to be tested
  47307. * @return {boolean} whether one (or more) of the triggers is handeled
  47308. */
  47309. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  47310. for (var index = 0; index < this.actions.length; index++) {
  47311. var action = this.actions[index];
  47312. if (triggers.indexOf(action.trigger) > -1) {
  47313. return true;
  47314. }
  47315. }
  47316. return false;
  47317. };
  47318. /**
  47319. * Does this action manager handles actions of a given trigger
  47320. * @param {number} trigger - the trigger to be tested
  47321. * @return {boolean} whether the trigger is handeled
  47322. */
  47323. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  47324. for (var index = 0; index < this.actions.length; index++) {
  47325. var action = this.actions[index];
  47326. if (action.trigger === trigger) {
  47327. return true;
  47328. }
  47329. }
  47330. return false;
  47331. };
  47332. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  47333. /**
  47334. * Does this action manager has pointer triggers
  47335. * @return {boolean} whether or not it has pointer triggers
  47336. */
  47337. get: function () {
  47338. for (var index = 0; index < this.actions.length; index++) {
  47339. var action = this.actions[index];
  47340. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  47341. return true;
  47342. }
  47343. }
  47344. return false;
  47345. },
  47346. enumerable: true,
  47347. configurable: true
  47348. });
  47349. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  47350. /**
  47351. * Does this action manager has pick triggers
  47352. * @return {boolean} whether or not it has pick triggers
  47353. */
  47354. get: function () {
  47355. for (var index = 0; index < this.actions.length; index++) {
  47356. var action = this.actions[index];
  47357. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  47358. return true;
  47359. }
  47360. }
  47361. return false;
  47362. },
  47363. enumerable: true,
  47364. configurable: true
  47365. });
  47366. Object.defineProperty(ActionManager, "HasTriggers", {
  47367. /**
  47368. * Does exist one action manager with at least one trigger
  47369. * @return {boolean} whether or not it exists one action manager with one trigger
  47370. **/
  47371. get: function () {
  47372. for (var t in ActionManager.Triggers) {
  47373. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47374. return true;
  47375. }
  47376. }
  47377. return false;
  47378. },
  47379. enumerable: true,
  47380. configurable: true
  47381. });
  47382. Object.defineProperty(ActionManager, "HasPickTriggers", {
  47383. /**
  47384. * Does exist one action manager with at least one pick trigger
  47385. * @return {boolean} whether or not it exists one action manager with one pick trigger
  47386. **/
  47387. get: function () {
  47388. for (var t in ActionManager.Triggers) {
  47389. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47390. var t_int = parseInt(t);
  47391. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  47392. return true;
  47393. }
  47394. }
  47395. }
  47396. return false;
  47397. },
  47398. enumerable: true,
  47399. configurable: true
  47400. });
  47401. /**
  47402. * Does exist one action manager that handles actions of a given trigger
  47403. * @param {number} trigger - the trigger to be tested
  47404. * @return {boolean} whether the trigger is handeled by at least one action manager
  47405. **/
  47406. ActionManager.HasSpecificTrigger = function (trigger) {
  47407. for (var t in ActionManager.Triggers) {
  47408. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47409. var t_int = parseInt(t);
  47410. if (t_int === trigger) {
  47411. return true;
  47412. }
  47413. }
  47414. }
  47415. return false;
  47416. };
  47417. /**
  47418. * Registers an action to this action manager
  47419. * @param {BABYLON.Action} action - the action to be registered
  47420. * @return {BABYLON.Action} the action amended (prepared) after registration
  47421. */
  47422. ActionManager.prototype.registerAction = function (action) {
  47423. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  47424. if (this.getScene().actionManager !== this) {
  47425. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  47426. return null;
  47427. }
  47428. }
  47429. this.actions.push(action);
  47430. if (ActionManager.Triggers[action.trigger]) {
  47431. ActionManager.Triggers[action.trigger]++;
  47432. }
  47433. else {
  47434. ActionManager.Triggers[action.trigger] = 1;
  47435. }
  47436. action._actionManager = this;
  47437. action._prepare();
  47438. return action;
  47439. };
  47440. /**
  47441. * Unregisters an action to this action manager
  47442. * @param action The action to be unregistered
  47443. * @return whether the action has been unregistered
  47444. */
  47445. ActionManager.prototype.unregisterAction = function (action) {
  47446. var index = this.actions.indexOf(action);
  47447. if (index !== -1) {
  47448. this.actions.splice(index, 1);
  47449. ActionManager.Triggers[action.trigger] -= 1;
  47450. if (ActionManager.Triggers[action.trigger] === 0) {
  47451. delete ActionManager.Triggers[action.trigger];
  47452. }
  47453. delete action._actionManager;
  47454. return true;
  47455. }
  47456. return false;
  47457. };
  47458. /**
  47459. * Process a specific trigger
  47460. * @param {number} trigger - the trigger to process
  47461. * @param evt {BABYLON.ActionEvent} the event details to be processed
  47462. */
  47463. ActionManager.prototype.processTrigger = function (trigger, evt) {
  47464. for (var index = 0; index < this.actions.length; index++) {
  47465. var action = this.actions[index];
  47466. if (action.trigger === trigger) {
  47467. if (evt) {
  47468. if (trigger === ActionManager.OnKeyUpTrigger
  47469. || trigger === ActionManager.OnKeyDownTrigger) {
  47470. var parameter = action.getTriggerParameter();
  47471. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  47472. if (!parameter.toLowerCase) {
  47473. continue;
  47474. }
  47475. var lowerCase = parameter.toLowerCase();
  47476. if (lowerCase !== evt.sourceEvent.key) {
  47477. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  47478. var actualkey = String.fromCharCode(unicode).toLowerCase();
  47479. if (actualkey !== lowerCase) {
  47480. continue;
  47481. }
  47482. }
  47483. }
  47484. }
  47485. }
  47486. action._executeCurrent(evt);
  47487. }
  47488. }
  47489. };
  47490. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  47491. var properties = propertyPath.split(".");
  47492. for (var index = 0; index < properties.length - 1; index++) {
  47493. target = target[properties[index]];
  47494. }
  47495. return target;
  47496. };
  47497. ActionManager.prototype._getProperty = function (propertyPath) {
  47498. var properties = propertyPath.split(".");
  47499. return properties[properties.length - 1];
  47500. };
  47501. ActionManager.prototype.serialize = function (name) {
  47502. var root = {
  47503. children: new Array(),
  47504. name: name,
  47505. type: 3,
  47506. properties: new Array() // Empty for root but required
  47507. };
  47508. for (var i = 0; i < this.actions.length; i++) {
  47509. var triggerObject = {
  47510. type: 0,
  47511. children: new Array(),
  47512. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  47513. properties: new Array()
  47514. };
  47515. var triggerOptions = this.actions[i].triggerOptions;
  47516. if (triggerOptions && typeof triggerOptions !== "number") {
  47517. if (triggerOptions.parameter instanceof BABYLON.Node) {
  47518. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  47519. }
  47520. else {
  47521. var parameter = {};
  47522. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  47523. if (triggerOptions.parameter.mesh) {
  47524. parameter._meshId = triggerOptions.parameter.mesh.id;
  47525. }
  47526. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  47527. }
  47528. }
  47529. // Serialize child action, recursively
  47530. this.actions[i].serialize(triggerObject);
  47531. // Add serialized trigger
  47532. root.children.push(triggerObject);
  47533. }
  47534. return root;
  47535. };
  47536. ActionManager.Parse = function (parsedActions, object, scene) {
  47537. var actionManager = new ActionManager(scene);
  47538. if (object === null)
  47539. scene.actionManager = actionManager;
  47540. else
  47541. object.actionManager = actionManager;
  47542. // instanciate a new object
  47543. var instanciate = function (name, params) {
  47544. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  47545. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  47546. newInstance.constructor.apply(newInstance, params);
  47547. return newInstance;
  47548. };
  47549. var parseParameter = function (name, value, target, propertyPath) {
  47550. if (propertyPath === null) {
  47551. // String, boolean or float
  47552. var floatValue = parseFloat(value);
  47553. if (value === "true" || value === "false")
  47554. return value === "true";
  47555. else
  47556. return isNaN(floatValue) ? value : floatValue;
  47557. }
  47558. var effectiveTarget = propertyPath.split(".");
  47559. var values = value.split(",");
  47560. // Get effective Target
  47561. for (var i = 0; i < effectiveTarget.length; i++) {
  47562. target = target[effectiveTarget[i]];
  47563. }
  47564. // Return appropriate value with its type
  47565. if (typeof (target) === "boolean")
  47566. return values[0] === "true";
  47567. if (typeof (target) === "string")
  47568. return values[0];
  47569. // Parameters with multiple values such as Vector3 etc.
  47570. var split = new Array();
  47571. for (var i = 0; i < values.length; i++)
  47572. split.push(parseFloat(values[i]));
  47573. if (target instanceof BABYLON.Vector3)
  47574. return BABYLON.Vector3.FromArray(split);
  47575. if (target instanceof BABYLON.Vector4)
  47576. return BABYLON.Vector4.FromArray(split);
  47577. if (target instanceof BABYLON.Color3)
  47578. return BABYLON.Color3.FromArray(split);
  47579. if (target instanceof BABYLON.Color4)
  47580. return BABYLON.Color4.FromArray(split);
  47581. return parseFloat(values[0]);
  47582. };
  47583. // traverse graph per trigger
  47584. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  47585. if (combineArray === void 0) { combineArray = null; }
  47586. if (parsedAction.detached)
  47587. return;
  47588. var parameters = new Array();
  47589. var target = null;
  47590. var propertyPath = null;
  47591. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  47592. // Parameters
  47593. if (parsedAction.type === 2)
  47594. parameters.push(actionManager);
  47595. else
  47596. parameters.push(trigger);
  47597. if (combine) {
  47598. var actions = new Array();
  47599. for (var j = 0; j < parsedAction.combine.length; j++) {
  47600. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  47601. }
  47602. parameters.push(actions);
  47603. }
  47604. else {
  47605. for (var i = 0; i < parsedAction.properties.length; i++) {
  47606. var value = parsedAction.properties[i].value;
  47607. var name = parsedAction.properties[i].name;
  47608. var targetType = parsedAction.properties[i].targetType;
  47609. if (name === "target")
  47610. if (targetType !== null && targetType === "SceneProperties")
  47611. value = target = scene;
  47612. else
  47613. value = target = scene.getNodeByName(value);
  47614. else if (name === "parent")
  47615. value = scene.getNodeByName(value);
  47616. else if (name === "sound")
  47617. value = scene.getSoundByName(value);
  47618. else if (name !== "propertyPath") {
  47619. if (parsedAction.type === 2 && name === "operator")
  47620. value = BABYLON.ValueCondition[value];
  47621. else
  47622. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  47623. }
  47624. else {
  47625. propertyPath = value;
  47626. }
  47627. parameters.push(value);
  47628. }
  47629. }
  47630. if (combineArray === null) {
  47631. parameters.push(condition);
  47632. }
  47633. else {
  47634. parameters.push(null);
  47635. }
  47636. // If interpolate value action
  47637. if (parsedAction.name === "InterpolateValueAction") {
  47638. var param = parameters[parameters.length - 2];
  47639. parameters[parameters.length - 1] = param;
  47640. parameters[parameters.length - 2] = condition;
  47641. }
  47642. // Action or condition(s) and not CombineAction
  47643. var newAction = instanciate(parsedAction.name, parameters);
  47644. if (newAction instanceof BABYLON.Condition && condition !== null) {
  47645. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  47646. if (action)
  47647. action.then(nothing);
  47648. else
  47649. actionManager.registerAction(nothing);
  47650. action = nothing;
  47651. }
  47652. if (combineArray === null) {
  47653. if (newAction instanceof BABYLON.Condition) {
  47654. condition = newAction;
  47655. newAction = action;
  47656. }
  47657. else {
  47658. condition = null;
  47659. if (action)
  47660. action.then(newAction);
  47661. else
  47662. actionManager.registerAction(newAction);
  47663. }
  47664. }
  47665. else {
  47666. combineArray.push(newAction);
  47667. }
  47668. for (var i = 0; i < parsedAction.children.length; i++)
  47669. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  47670. };
  47671. // triggers
  47672. for (var i = 0; i < parsedActions.children.length; i++) {
  47673. var triggerParams;
  47674. var trigger = parsedActions.children[i];
  47675. if (trigger.properties.length > 0) {
  47676. var param = trigger.properties[0].value;
  47677. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  47678. if (value._meshId) {
  47679. value.mesh = scene.getMeshByID(value._meshId);
  47680. }
  47681. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  47682. }
  47683. else
  47684. triggerParams = ActionManager[trigger.name];
  47685. for (var j = 0; j < trigger.children.length; j++) {
  47686. if (!trigger.detached)
  47687. traverse(trigger.children[j], triggerParams, null, null);
  47688. }
  47689. }
  47690. };
  47691. ActionManager.GetTriggerName = function (trigger) {
  47692. switch (trigger) {
  47693. case 0: return "NothingTrigger";
  47694. case 1: return "OnPickTrigger";
  47695. case 2: return "OnLeftPickTrigger";
  47696. case 3: return "OnRightPickTrigger";
  47697. case 4: return "OnCenterPickTrigger";
  47698. case 5: return "OnPickDownTrigger";
  47699. case 6: return "OnPickUpTrigger";
  47700. case 7: return "OnLongPressTrigger";
  47701. case 8: return "OnPointerOverTrigger";
  47702. case 9: return "OnPointerOutTrigger";
  47703. case 10: return "OnEveryFrameTrigger";
  47704. case 11: return "OnIntersectionEnterTrigger";
  47705. case 12: return "OnIntersectionExitTrigger";
  47706. case 13: return "OnKeyDownTrigger";
  47707. case 14: return "OnKeyUpTrigger";
  47708. case 15: return "OnPickOutTrigger";
  47709. default: return "";
  47710. }
  47711. };
  47712. // Statics
  47713. ActionManager._NothingTrigger = 0;
  47714. ActionManager._OnPickTrigger = 1;
  47715. ActionManager._OnLeftPickTrigger = 2;
  47716. ActionManager._OnRightPickTrigger = 3;
  47717. ActionManager._OnCenterPickTrigger = 4;
  47718. ActionManager._OnPickDownTrigger = 5;
  47719. ActionManager._OnDoublePickTrigger = 6;
  47720. ActionManager._OnPickUpTrigger = 7;
  47721. ActionManager._OnLongPressTrigger = 8;
  47722. ActionManager._OnPointerOverTrigger = 9;
  47723. ActionManager._OnPointerOutTrigger = 10;
  47724. ActionManager._OnEveryFrameTrigger = 11;
  47725. ActionManager._OnIntersectionEnterTrigger = 12;
  47726. ActionManager._OnIntersectionExitTrigger = 13;
  47727. ActionManager._OnKeyDownTrigger = 14;
  47728. ActionManager._OnKeyUpTrigger = 15;
  47729. ActionManager._OnPickOutTrigger = 16;
  47730. ActionManager.Triggers = {};
  47731. return ActionManager;
  47732. }());
  47733. BABYLON.ActionManager = ActionManager;
  47734. })(BABYLON || (BABYLON = {}));
  47735. //# sourceMappingURL=babylon.actionManager.js.map
  47736. var BABYLON;
  47737. (function (BABYLON) {
  47738. var InterpolateValueAction = /** @class */ (function (_super) {
  47739. __extends(InterpolateValueAction, _super);
  47740. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  47741. if (duration === void 0) { duration = 1000; }
  47742. var _this = _super.call(this, triggerOptions, condition) || this;
  47743. _this.propertyPath = propertyPath;
  47744. _this.value = value;
  47745. _this.duration = duration;
  47746. _this.stopOtherAnimations = stopOtherAnimations;
  47747. _this.onInterpolationDone = onInterpolationDone;
  47748. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  47749. _this._target = _this._effectiveTarget = target;
  47750. return _this;
  47751. }
  47752. InterpolateValueAction.prototype._prepare = function () {
  47753. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  47754. this._property = this._getProperty(this.propertyPath);
  47755. };
  47756. InterpolateValueAction.prototype.execute = function () {
  47757. var _this = this;
  47758. var scene = this._actionManager.getScene();
  47759. var keys = [
  47760. {
  47761. frame: 0,
  47762. value: this._effectiveTarget[this._property]
  47763. }, {
  47764. frame: 100,
  47765. value: this.value
  47766. }
  47767. ];
  47768. var dataType;
  47769. if (typeof this.value === "number") {
  47770. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  47771. }
  47772. else if (this.value instanceof BABYLON.Color3) {
  47773. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  47774. }
  47775. else if (this.value instanceof BABYLON.Vector3) {
  47776. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  47777. }
  47778. else if (this.value instanceof BABYLON.Matrix) {
  47779. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  47780. }
  47781. else if (this.value instanceof BABYLON.Quaternion) {
  47782. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  47783. }
  47784. else {
  47785. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  47786. return;
  47787. }
  47788. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  47789. animation.setKeys(keys);
  47790. if (this.stopOtherAnimations) {
  47791. scene.stopAnimation(this._effectiveTarget);
  47792. }
  47793. var wrapper = function () {
  47794. _this.onInterpolationDoneObservable.notifyObservers(_this);
  47795. if (_this.onInterpolationDone) {
  47796. _this.onInterpolationDone();
  47797. }
  47798. };
  47799. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  47800. };
  47801. InterpolateValueAction.prototype.serialize = function (parent) {
  47802. return _super.prototype._serialize.call(this, {
  47803. name: "InterpolateValueAction",
  47804. properties: [
  47805. BABYLON.Action._GetTargetProperty(this._target),
  47806. { name: "propertyPath", value: this.propertyPath },
  47807. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  47808. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  47809. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  47810. ]
  47811. }, parent);
  47812. };
  47813. return InterpolateValueAction;
  47814. }(BABYLON.Action));
  47815. BABYLON.InterpolateValueAction = InterpolateValueAction;
  47816. })(BABYLON || (BABYLON = {}));
  47817. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  47818. var BABYLON;
  47819. (function (BABYLON) {
  47820. var SwitchBooleanAction = /** @class */ (function (_super) {
  47821. __extends(SwitchBooleanAction, _super);
  47822. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  47823. var _this = _super.call(this, triggerOptions, condition) || this;
  47824. _this.propertyPath = propertyPath;
  47825. _this._target = _this._effectiveTarget = target;
  47826. return _this;
  47827. }
  47828. SwitchBooleanAction.prototype._prepare = function () {
  47829. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  47830. this._property = this._getProperty(this.propertyPath);
  47831. };
  47832. SwitchBooleanAction.prototype.execute = function () {
  47833. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  47834. };
  47835. SwitchBooleanAction.prototype.serialize = function (parent) {
  47836. return _super.prototype._serialize.call(this, {
  47837. name: "SwitchBooleanAction",
  47838. properties: [
  47839. BABYLON.Action._GetTargetProperty(this._target),
  47840. { name: "propertyPath", value: this.propertyPath }
  47841. ]
  47842. }, parent);
  47843. };
  47844. return SwitchBooleanAction;
  47845. }(BABYLON.Action));
  47846. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  47847. var SetStateAction = /** @class */ (function (_super) {
  47848. __extends(SetStateAction, _super);
  47849. function SetStateAction(triggerOptions, target, value, condition) {
  47850. var _this = _super.call(this, triggerOptions, condition) || this;
  47851. _this.value = value;
  47852. _this._target = target;
  47853. return _this;
  47854. }
  47855. SetStateAction.prototype.execute = function () {
  47856. this._target.state = this.value;
  47857. };
  47858. SetStateAction.prototype.serialize = function (parent) {
  47859. return _super.prototype._serialize.call(this, {
  47860. name: "SetStateAction",
  47861. properties: [
  47862. BABYLON.Action._GetTargetProperty(this._target),
  47863. { name: "value", value: this.value }
  47864. ]
  47865. }, parent);
  47866. };
  47867. return SetStateAction;
  47868. }(BABYLON.Action));
  47869. BABYLON.SetStateAction = SetStateAction;
  47870. var SetValueAction = /** @class */ (function (_super) {
  47871. __extends(SetValueAction, _super);
  47872. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  47873. var _this = _super.call(this, triggerOptions, condition) || this;
  47874. _this.propertyPath = propertyPath;
  47875. _this.value = value;
  47876. _this._target = _this._effectiveTarget = target;
  47877. return _this;
  47878. }
  47879. SetValueAction.prototype._prepare = function () {
  47880. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  47881. this._property = this._getProperty(this.propertyPath);
  47882. };
  47883. SetValueAction.prototype.execute = function () {
  47884. this._effectiveTarget[this._property] = this.value;
  47885. if (this._target.markAsDirty) {
  47886. this._target.markAsDirty(this._property);
  47887. }
  47888. };
  47889. SetValueAction.prototype.serialize = function (parent) {
  47890. return _super.prototype._serialize.call(this, {
  47891. name: "SetValueAction",
  47892. properties: [
  47893. BABYLON.Action._GetTargetProperty(this._target),
  47894. { name: "propertyPath", value: this.propertyPath },
  47895. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  47896. ]
  47897. }, parent);
  47898. };
  47899. return SetValueAction;
  47900. }(BABYLON.Action));
  47901. BABYLON.SetValueAction = SetValueAction;
  47902. var IncrementValueAction = /** @class */ (function (_super) {
  47903. __extends(IncrementValueAction, _super);
  47904. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  47905. var _this = _super.call(this, triggerOptions, condition) || this;
  47906. _this.propertyPath = propertyPath;
  47907. _this.value = value;
  47908. _this._target = _this._effectiveTarget = target;
  47909. return _this;
  47910. }
  47911. IncrementValueAction.prototype._prepare = function () {
  47912. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  47913. this._property = this._getProperty(this.propertyPath);
  47914. if (typeof this._effectiveTarget[this._property] !== "number") {
  47915. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  47916. }
  47917. };
  47918. IncrementValueAction.prototype.execute = function () {
  47919. this._effectiveTarget[this._property] += this.value;
  47920. if (this._target.markAsDirty) {
  47921. this._target.markAsDirty(this._property);
  47922. }
  47923. };
  47924. IncrementValueAction.prototype.serialize = function (parent) {
  47925. return _super.prototype._serialize.call(this, {
  47926. name: "IncrementValueAction",
  47927. properties: [
  47928. BABYLON.Action._GetTargetProperty(this._target),
  47929. { name: "propertyPath", value: this.propertyPath },
  47930. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  47931. ]
  47932. }, parent);
  47933. };
  47934. return IncrementValueAction;
  47935. }(BABYLON.Action));
  47936. BABYLON.IncrementValueAction = IncrementValueAction;
  47937. var PlayAnimationAction = /** @class */ (function (_super) {
  47938. __extends(PlayAnimationAction, _super);
  47939. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  47940. var _this = _super.call(this, triggerOptions, condition) || this;
  47941. _this.from = from;
  47942. _this.to = to;
  47943. _this.loop = loop;
  47944. _this._target = target;
  47945. return _this;
  47946. }
  47947. PlayAnimationAction.prototype._prepare = function () {
  47948. };
  47949. PlayAnimationAction.prototype.execute = function () {
  47950. var scene = this._actionManager.getScene();
  47951. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  47952. };
  47953. PlayAnimationAction.prototype.serialize = function (parent) {
  47954. return _super.prototype._serialize.call(this, {
  47955. name: "PlayAnimationAction",
  47956. properties: [
  47957. BABYLON.Action._GetTargetProperty(this._target),
  47958. { name: "from", value: String(this.from) },
  47959. { name: "to", value: String(this.to) },
  47960. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  47961. ]
  47962. }, parent);
  47963. };
  47964. return PlayAnimationAction;
  47965. }(BABYLON.Action));
  47966. BABYLON.PlayAnimationAction = PlayAnimationAction;
  47967. var StopAnimationAction = /** @class */ (function (_super) {
  47968. __extends(StopAnimationAction, _super);
  47969. function StopAnimationAction(triggerOptions, target, condition) {
  47970. var _this = _super.call(this, triggerOptions, condition) || this;
  47971. _this._target = target;
  47972. return _this;
  47973. }
  47974. StopAnimationAction.prototype._prepare = function () {
  47975. };
  47976. StopAnimationAction.prototype.execute = function () {
  47977. var scene = this._actionManager.getScene();
  47978. scene.stopAnimation(this._target);
  47979. };
  47980. StopAnimationAction.prototype.serialize = function (parent) {
  47981. return _super.prototype._serialize.call(this, {
  47982. name: "StopAnimationAction",
  47983. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  47984. }, parent);
  47985. };
  47986. return StopAnimationAction;
  47987. }(BABYLON.Action));
  47988. BABYLON.StopAnimationAction = StopAnimationAction;
  47989. var DoNothingAction = /** @class */ (function (_super) {
  47990. __extends(DoNothingAction, _super);
  47991. function DoNothingAction(triggerOptions, condition) {
  47992. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  47993. return _super.call(this, triggerOptions, condition) || this;
  47994. }
  47995. DoNothingAction.prototype.execute = function () {
  47996. };
  47997. DoNothingAction.prototype.serialize = function (parent) {
  47998. return _super.prototype._serialize.call(this, {
  47999. name: "DoNothingAction",
  48000. properties: []
  48001. }, parent);
  48002. };
  48003. return DoNothingAction;
  48004. }(BABYLON.Action));
  48005. BABYLON.DoNothingAction = DoNothingAction;
  48006. var CombineAction = /** @class */ (function (_super) {
  48007. __extends(CombineAction, _super);
  48008. function CombineAction(triggerOptions, children, condition) {
  48009. var _this = _super.call(this, triggerOptions, condition) || this;
  48010. _this.children = children;
  48011. return _this;
  48012. }
  48013. CombineAction.prototype._prepare = function () {
  48014. for (var index = 0; index < this.children.length; index++) {
  48015. this.children[index]._actionManager = this._actionManager;
  48016. this.children[index]._prepare();
  48017. }
  48018. };
  48019. CombineAction.prototype.execute = function (evt) {
  48020. for (var index = 0; index < this.children.length; index++) {
  48021. this.children[index].execute(evt);
  48022. }
  48023. };
  48024. CombineAction.prototype.serialize = function (parent) {
  48025. var serializationObject = _super.prototype._serialize.call(this, {
  48026. name: "CombineAction",
  48027. properties: [],
  48028. combine: []
  48029. }, parent);
  48030. for (var i = 0; i < this.children.length; i++) {
  48031. serializationObject.combine.push(this.children[i].serialize(null));
  48032. }
  48033. return serializationObject;
  48034. };
  48035. return CombineAction;
  48036. }(BABYLON.Action));
  48037. BABYLON.CombineAction = CombineAction;
  48038. var ExecuteCodeAction = /** @class */ (function (_super) {
  48039. __extends(ExecuteCodeAction, _super);
  48040. function ExecuteCodeAction(triggerOptions, func, condition) {
  48041. var _this = _super.call(this, triggerOptions, condition) || this;
  48042. _this.func = func;
  48043. return _this;
  48044. }
  48045. ExecuteCodeAction.prototype.execute = function (evt) {
  48046. this.func(evt);
  48047. };
  48048. return ExecuteCodeAction;
  48049. }(BABYLON.Action));
  48050. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  48051. var SetParentAction = /** @class */ (function (_super) {
  48052. __extends(SetParentAction, _super);
  48053. function SetParentAction(triggerOptions, target, parent, condition) {
  48054. var _this = _super.call(this, triggerOptions, condition) || this;
  48055. _this._target = target;
  48056. _this._parent = parent;
  48057. return _this;
  48058. }
  48059. SetParentAction.prototype._prepare = function () {
  48060. };
  48061. SetParentAction.prototype.execute = function () {
  48062. if (this._target.parent === this._parent) {
  48063. return;
  48064. }
  48065. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  48066. invertParentWorldMatrix.invert();
  48067. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  48068. this._target.parent = this._parent;
  48069. };
  48070. SetParentAction.prototype.serialize = function (parent) {
  48071. return _super.prototype._serialize.call(this, {
  48072. name: "SetParentAction",
  48073. properties: [
  48074. BABYLON.Action._GetTargetProperty(this._target),
  48075. BABYLON.Action._GetTargetProperty(this._parent),
  48076. ]
  48077. }, parent);
  48078. };
  48079. return SetParentAction;
  48080. }(BABYLON.Action));
  48081. BABYLON.SetParentAction = SetParentAction;
  48082. var PlaySoundAction = /** @class */ (function (_super) {
  48083. __extends(PlaySoundAction, _super);
  48084. function PlaySoundAction(triggerOptions, sound, condition) {
  48085. var _this = _super.call(this, triggerOptions, condition) || this;
  48086. _this._sound = sound;
  48087. return _this;
  48088. }
  48089. PlaySoundAction.prototype._prepare = function () {
  48090. };
  48091. PlaySoundAction.prototype.execute = function () {
  48092. if (this._sound !== undefined)
  48093. this._sound.play();
  48094. };
  48095. PlaySoundAction.prototype.serialize = function (parent) {
  48096. return _super.prototype._serialize.call(this, {
  48097. name: "PlaySoundAction",
  48098. properties: [{ name: "sound", value: this._sound.name }]
  48099. }, parent);
  48100. };
  48101. return PlaySoundAction;
  48102. }(BABYLON.Action));
  48103. BABYLON.PlaySoundAction = PlaySoundAction;
  48104. var StopSoundAction = /** @class */ (function (_super) {
  48105. __extends(StopSoundAction, _super);
  48106. function StopSoundAction(triggerOptions, sound, condition) {
  48107. var _this = _super.call(this, triggerOptions, condition) || this;
  48108. _this._sound = sound;
  48109. return _this;
  48110. }
  48111. StopSoundAction.prototype._prepare = function () {
  48112. };
  48113. StopSoundAction.prototype.execute = function () {
  48114. if (this._sound !== undefined)
  48115. this._sound.stop();
  48116. };
  48117. StopSoundAction.prototype.serialize = function (parent) {
  48118. return _super.prototype._serialize.call(this, {
  48119. name: "StopSoundAction",
  48120. properties: [{ name: "sound", value: this._sound.name }]
  48121. }, parent);
  48122. };
  48123. return StopSoundAction;
  48124. }(BABYLON.Action));
  48125. BABYLON.StopSoundAction = StopSoundAction;
  48126. })(BABYLON || (BABYLON = {}));
  48127. //# sourceMappingURL=babylon.directActions.js.map
  48128. var BABYLON;
  48129. (function (BABYLON) {
  48130. var SpriteManager = /** @class */ (function () {
  48131. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  48132. if (epsilon === void 0) { epsilon = 0.01; }
  48133. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48134. this.name = name;
  48135. this.sprites = new Array();
  48136. this.renderingGroupId = 0;
  48137. this.layerMask = 0x0FFFFFFF;
  48138. this.fogEnabled = true;
  48139. this.isPickable = false;
  48140. /**
  48141. * An event triggered when the manager is disposed.
  48142. * @type {BABYLON.Observable}
  48143. */
  48144. this.onDisposeObservable = new BABYLON.Observable();
  48145. this._vertexBuffers = {};
  48146. this._capacity = capacity;
  48147. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  48148. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48149. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48150. if (cellSize.width && cellSize.height) {
  48151. this.cellWidth = cellSize.width;
  48152. this.cellHeight = cellSize.height;
  48153. }
  48154. else if (cellSize !== undefined) {
  48155. this.cellWidth = cellSize;
  48156. this.cellHeight = cellSize;
  48157. }
  48158. else {
  48159. return;
  48160. }
  48161. this._epsilon = epsilon;
  48162. this._scene = scene;
  48163. this._scene.spriteManagers.push(this);
  48164. var indices = [];
  48165. var index = 0;
  48166. for (var count = 0; count < capacity; count++) {
  48167. indices.push(index);
  48168. indices.push(index + 1);
  48169. indices.push(index + 2);
  48170. indices.push(index);
  48171. indices.push(index + 2);
  48172. indices.push(index + 3);
  48173. index += 4;
  48174. }
  48175. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  48176. // VBO
  48177. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  48178. this._vertexData = new Float32Array(capacity * 16 * 4);
  48179. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  48180. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  48181. var options = this._buffer.createVertexBuffer("options", 4, 4);
  48182. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  48183. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  48184. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  48185. this._vertexBuffers["options"] = options;
  48186. this._vertexBuffers["cellInfo"] = cellInfo;
  48187. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  48188. // Effects
  48189. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  48190. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  48191. }
  48192. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  48193. set: function (callback) {
  48194. if (this._onDisposeObserver) {
  48195. this.onDisposeObservable.remove(this._onDisposeObserver);
  48196. }
  48197. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  48198. },
  48199. enumerable: true,
  48200. configurable: true
  48201. });
  48202. Object.defineProperty(SpriteManager.prototype, "texture", {
  48203. get: function () {
  48204. return this._spriteTexture;
  48205. },
  48206. set: function (value) {
  48207. this._spriteTexture = value;
  48208. },
  48209. enumerable: true,
  48210. configurable: true
  48211. });
  48212. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  48213. var arrayOffset = index * 16;
  48214. if (offsetX === 0)
  48215. offsetX = this._epsilon;
  48216. else if (offsetX === 1)
  48217. offsetX = 1 - this._epsilon;
  48218. if (offsetY === 0)
  48219. offsetY = this._epsilon;
  48220. else if (offsetY === 1)
  48221. offsetY = 1 - this._epsilon;
  48222. this._vertexData[arrayOffset] = sprite.position.x;
  48223. this._vertexData[arrayOffset + 1] = sprite.position.y;
  48224. this._vertexData[arrayOffset + 2] = sprite.position.z;
  48225. this._vertexData[arrayOffset + 3] = sprite.angle;
  48226. this._vertexData[arrayOffset + 4] = sprite.width;
  48227. this._vertexData[arrayOffset + 5] = sprite.height;
  48228. this._vertexData[arrayOffset + 6] = offsetX;
  48229. this._vertexData[arrayOffset + 7] = offsetY;
  48230. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  48231. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  48232. var offset = (sprite.cellIndex / rowSize) >> 0;
  48233. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  48234. this._vertexData[arrayOffset + 11] = offset;
  48235. // Color
  48236. this._vertexData[arrayOffset + 12] = sprite.color.r;
  48237. this._vertexData[arrayOffset + 13] = sprite.color.g;
  48238. this._vertexData[arrayOffset + 14] = sprite.color.b;
  48239. this._vertexData[arrayOffset + 15] = sprite.color.a;
  48240. };
  48241. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  48242. var count = Math.min(this._capacity, this.sprites.length);
  48243. var min = BABYLON.Vector3.Zero();
  48244. var max = BABYLON.Vector3.Zero();
  48245. var distance = Number.MAX_VALUE;
  48246. var currentSprite = null;
  48247. var cameraSpacePosition = BABYLON.Vector3.Zero();
  48248. var cameraView = camera.getViewMatrix();
  48249. for (var index = 0; index < count; index++) {
  48250. var sprite = this.sprites[index];
  48251. if (!sprite) {
  48252. continue;
  48253. }
  48254. if (predicate) {
  48255. if (!predicate(sprite)) {
  48256. continue;
  48257. }
  48258. }
  48259. else if (!sprite.isPickable) {
  48260. continue;
  48261. }
  48262. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  48263. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  48264. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  48265. if (ray.intersectsBoxMinMax(min, max)) {
  48266. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  48267. if (distance > currentDistance) {
  48268. distance = currentDistance;
  48269. currentSprite = sprite;
  48270. if (fastCheck) {
  48271. break;
  48272. }
  48273. }
  48274. }
  48275. }
  48276. if (currentSprite) {
  48277. var result = new BABYLON.PickingInfo();
  48278. result.hit = true;
  48279. result.pickedSprite = currentSprite;
  48280. result.distance = distance;
  48281. return result;
  48282. }
  48283. return null;
  48284. };
  48285. SpriteManager.prototype.render = function () {
  48286. // Check
  48287. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  48288. return;
  48289. var engine = this._scene.getEngine();
  48290. var baseSize = this._spriteTexture.getBaseSize();
  48291. // Sprites
  48292. var deltaTime = engine.getDeltaTime();
  48293. var max = Math.min(this._capacity, this.sprites.length);
  48294. var rowSize = baseSize.width / this.cellWidth;
  48295. var offset = 0;
  48296. for (var index = 0; index < max; index++) {
  48297. var sprite = this.sprites[index];
  48298. if (!sprite) {
  48299. continue;
  48300. }
  48301. sprite._animate(deltaTime);
  48302. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  48303. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  48304. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  48305. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  48306. }
  48307. this._buffer.update(this._vertexData);
  48308. // Render
  48309. var effect = this._effectBase;
  48310. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48311. effect = this._effectFog;
  48312. }
  48313. engine.enableEffect(effect);
  48314. var viewMatrix = this._scene.getViewMatrix();
  48315. effect.setTexture("diffuseSampler", this._spriteTexture);
  48316. effect.setMatrix("view", viewMatrix);
  48317. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  48318. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  48319. // Fog
  48320. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48321. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  48322. effect.setColor3("vFogColor", this._scene.fogColor);
  48323. }
  48324. // VBOs
  48325. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  48326. // Draw order
  48327. engine.setDepthFunctionToLessOrEqual();
  48328. effect.setBool("alphaTest", true);
  48329. engine.setColorWrite(false);
  48330. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48331. engine.setColorWrite(true);
  48332. effect.setBool("alphaTest", false);
  48333. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48334. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48335. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48336. };
  48337. SpriteManager.prototype.dispose = function () {
  48338. if (this._buffer) {
  48339. this._buffer.dispose();
  48340. this._buffer = null;
  48341. }
  48342. if (this._indexBuffer) {
  48343. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  48344. this._indexBuffer = null;
  48345. }
  48346. if (this._spriteTexture) {
  48347. this._spriteTexture.dispose();
  48348. this._spriteTexture = null;
  48349. }
  48350. // Remove from scene
  48351. var index = this._scene.spriteManagers.indexOf(this);
  48352. this._scene.spriteManagers.splice(index, 1);
  48353. // Callback
  48354. this.onDisposeObservable.notifyObservers(this);
  48355. this.onDisposeObservable.clear();
  48356. };
  48357. return SpriteManager;
  48358. }());
  48359. BABYLON.SpriteManager = SpriteManager;
  48360. })(BABYLON || (BABYLON = {}));
  48361. //# sourceMappingURL=babylon.spriteManager.js.map
  48362. var BABYLON;
  48363. (function (BABYLON) {
  48364. var Sprite = /** @class */ (function () {
  48365. function Sprite(name, manager) {
  48366. this.name = name;
  48367. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48368. this.width = 1.0;
  48369. this.height = 1.0;
  48370. this.angle = 0;
  48371. this.cellIndex = 0;
  48372. this.invertU = 0;
  48373. this.invertV = 0;
  48374. this.animations = new Array();
  48375. this.isPickable = false;
  48376. this._animationStarted = false;
  48377. this._loopAnimation = false;
  48378. this._fromIndex = 0;
  48379. this._toIndex = 0;
  48380. this._delay = 0;
  48381. this._direction = 1;
  48382. this._time = 0;
  48383. this._manager = manager;
  48384. this._manager.sprites.push(this);
  48385. this.position = BABYLON.Vector3.Zero();
  48386. }
  48387. Object.defineProperty(Sprite.prototype, "size", {
  48388. get: function () {
  48389. return this.width;
  48390. },
  48391. set: function (value) {
  48392. this.width = value;
  48393. this.height = value;
  48394. },
  48395. enumerable: true,
  48396. configurable: true
  48397. });
  48398. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  48399. this._fromIndex = from;
  48400. this._toIndex = to;
  48401. this._loopAnimation = loop;
  48402. this._delay = delay;
  48403. this._animationStarted = true;
  48404. this._direction = from < to ? 1 : -1;
  48405. this.cellIndex = from;
  48406. this._time = 0;
  48407. this._onAnimationEnd = onAnimationEnd;
  48408. };
  48409. Sprite.prototype.stopAnimation = function () {
  48410. this._animationStarted = false;
  48411. };
  48412. Sprite.prototype._animate = function (deltaTime) {
  48413. if (!this._animationStarted)
  48414. return;
  48415. this._time += deltaTime;
  48416. if (this._time > this._delay) {
  48417. this._time = this._time % this._delay;
  48418. this.cellIndex += this._direction;
  48419. if (this.cellIndex > this._toIndex) {
  48420. if (this._loopAnimation) {
  48421. this.cellIndex = this._fromIndex;
  48422. }
  48423. else {
  48424. this.cellIndex = this._toIndex;
  48425. this._animationStarted = false;
  48426. if (this._onAnimationEnd) {
  48427. this._onAnimationEnd();
  48428. }
  48429. if (this.disposeWhenFinishedAnimating) {
  48430. this.dispose();
  48431. }
  48432. }
  48433. }
  48434. }
  48435. };
  48436. Sprite.prototype.dispose = function () {
  48437. for (var i = 0; i < this._manager.sprites.length; i++) {
  48438. if (this._manager.sprites[i] == this) {
  48439. this._manager.sprites.splice(i, 1);
  48440. }
  48441. }
  48442. };
  48443. return Sprite;
  48444. }());
  48445. BABYLON.Sprite = Sprite;
  48446. })(BABYLON || (BABYLON = {}));
  48447. //# sourceMappingURL=babylon.sprite.js.map
  48448. var BABYLON;
  48449. (function (BABYLON) {
  48450. var IntersectionInfo = /** @class */ (function () {
  48451. function IntersectionInfo(bu, bv, distance) {
  48452. this.bu = bu;
  48453. this.bv = bv;
  48454. this.distance = distance;
  48455. this.faceId = 0;
  48456. this.subMeshId = 0;
  48457. }
  48458. return IntersectionInfo;
  48459. }());
  48460. BABYLON.IntersectionInfo = IntersectionInfo;
  48461. var PickingInfo = /** @class */ (function () {
  48462. function PickingInfo() {
  48463. this.hit = false;
  48464. this.distance = 0;
  48465. this.pickedPoint = null;
  48466. this.pickedMesh = null;
  48467. this.bu = 0;
  48468. this.bv = 0;
  48469. this.faceId = -1;
  48470. this.subMeshId = 0;
  48471. this.pickedSprite = null;
  48472. }
  48473. // Methods
  48474. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  48475. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  48476. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  48477. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  48478. return null;
  48479. }
  48480. var indices = this.pickedMesh.getIndices();
  48481. if (!indices) {
  48482. return null;
  48483. }
  48484. var result;
  48485. if (useVerticesNormals) {
  48486. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48487. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  48488. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  48489. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  48490. normal0 = normal0.scale(this.bu);
  48491. normal1 = normal1.scale(this.bv);
  48492. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  48493. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  48494. }
  48495. else {
  48496. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48497. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  48498. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  48499. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  48500. var p1p2 = vertex1.subtract(vertex2);
  48501. var p3p2 = vertex3.subtract(vertex2);
  48502. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  48503. }
  48504. if (useWorldCoordinates) {
  48505. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  48506. }
  48507. return BABYLON.Vector3.Normalize(result);
  48508. };
  48509. PickingInfo.prototype.getTextureCoordinates = function () {
  48510. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  48511. return null;
  48512. }
  48513. var indices = this.pickedMesh.getIndices();
  48514. if (!indices) {
  48515. return null;
  48516. }
  48517. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48518. if (!uvs) {
  48519. return null;
  48520. }
  48521. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  48522. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  48523. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  48524. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  48525. uv1 = uv1.scale(this.bu);
  48526. uv2 = uv2.scale(this.bv);
  48527. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  48528. };
  48529. return PickingInfo;
  48530. }());
  48531. BABYLON.PickingInfo = PickingInfo;
  48532. })(BABYLON || (BABYLON = {}));
  48533. //# sourceMappingURL=babylon.pickingInfo.js.map
  48534. var BABYLON;
  48535. (function (BABYLON) {
  48536. var Ray = /** @class */ (function () {
  48537. function Ray(origin, direction, length) {
  48538. if (length === void 0) { length = Number.MAX_VALUE; }
  48539. this.origin = origin;
  48540. this.direction = direction;
  48541. this.length = length;
  48542. }
  48543. // Methods
  48544. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  48545. var d = 0.0;
  48546. var maxValue = Number.MAX_VALUE;
  48547. var inv;
  48548. var min;
  48549. var max;
  48550. var temp;
  48551. if (Math.abs(this.direction.x) < 0.0000001) {
  48552. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  48553. return false;
  48554. }
  48555. }
  48556. else {
  48557. inv = 1.0 / this.direction.x;
  48558. min = (minimum.x - this.origin.x) * inv;
  48559. max = (maximum.x - this.origin.x) * inv;
  48560. if (max === -Infinity) {
  48561. max = Infinity;
  48562. }
  48563. if (min > max) {
  48564. temp = min;
  48565. min = max;
  48566. max = temp;
  48567. }
  48568. d = Math.max(min, d);
  48569. maxValue = Math.min(max, maxValue);
  48570. if (d > maxValue) {
  48571. return false;
  48572. }
  48573. }
  48574. if (Math.abs(this.direction.y) < 0.0000001) {
  48575. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  48576. return false;
  48577. }
  48578. }
  48579. else {
  48580. inv = 1.0 / this.direction.y;
  48581. min = (minimum.y - this.origin.y) * inv;
  48582. max = (maximum.y - this.origin.y) * inv;
  48583. if (max === -Infinity) {
  48584. max = Infinity;
  48585. }
  48586. if (min > max) {
  48587. temp = min;
  48588. min = max;
  48589. max = temp;
  48590. }
  48591. d = Math.max(min, d);
  48592. maxValue = Math.min(max, maxValue);
  48593. if (d > maxValue) {
  48594. return false;
  48595. }
  48596. }
  48597. if (Math.abs(this.direction.z) < 0.0000001) {
  48598. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  48599. return false;
  48600. }
  48601. }
  48602. else {
  48603. inv = 1.0 / this.direction.z;
  48604. min = (minimum.z - this.origin.z) * inv;
  48605. max = (maximum.z - this.origin.z) * inv;
  48606. if (max === -Infinity) {
  48607. max = Infinity;
  48608. }
  48609. if (min > max) {
  48610. temp = min;
  48611. min = max;
  48612. max = temp;
  48613. }
  48614. d = Math.max(min, d);
  48615. maxValue = Math.min(max, maxValue);
  48616. if (d > maxValue) {
  48617. return false;
  48618. }
  48619. }
  48620. return true;
  48621. };
  48622. Ray.prototype.intersectsBox = function (box) {
  48623. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  48624. };
  48625. Ray.prototype.intersectsSphere = function (sphere) {
  48626. var x = sphere.center.x - this.origin.x;
  48627. var y = sphere.center.y - this.origin.y;
  48628. var z = sphere.center.z - this.origin.z;
  48629. var pyth = (x * x) + (y * y) + (z * z);
  48630. var rr = sphere.radius * sphere.radius;
  48631. if (pyth <= rr) {
  48632. return true;
  48633. }
  48634. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  48635. if (dot < 0.0) {
  48636. return false;
  48637. }
  48638. var temp = pyth - (dot * dot);
  48639. return temp <= rr;
  48640. };
  48641. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  48642. if (!this._edge1) {
  48643. this._edge1 = BABYLON.Vector3.Zero();
  48644. this._edge2 = BABYLON.Vector3.Zero();
  48645. this._pvec = BABYLON.Vector3.Zero();
  48646. this._tvec = BABYLON.Vector3.Zero();
  48647. this._qvec = BABYLON.Vector3.Zero();
  48648. }
  48649. vertex1.subtractToRef(vertex0, this._edge1);
  48650. vertex2.subtractToRef(vertex0, this._edge2);
  48651. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  48652. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  48653. if (det === 0) {
  48654. return null;
  48655. }
  48656. var invdet = 1 / det;
  48657. this.origin.subtractToRef(vertex0, this._tvec);
  48658. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  48659. if (bu < 0 || bu > 1.0) {
  48660. return null;
  48661. }
  48662. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  48663. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  48664. if (bv < 0 || bu + bv > 1.0) {
  48665. return null;
  48666. }
  48667. //check if the distance is longer than the predefined length.
  48668. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  48669. if (distance > this.length) {
  48670. return null;
  48671. }
  48672. return new BABYLON.IntersectionInfo(bu, bv, distance);
  48673. };
  48674. Ray.prototype.intersectsPlane = function (plane) {
  48675. var distance;
  48676. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  48677. if (Math.abs(result1) < 9.99999997475243E-07) {
  48678. return null;
  48679. }
  48680. else {
  48681. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  48682. distance = (-plane.d - result2) / result1;
  48683. if (distance < 0.0) {
  48684. if (distance < -9.99999997475243E-07) {
  48685. return null;
  48686. }
  48687. else {
  48688. return 0;
  48689. }
  48690. }
  48691. return distance;
  48692. }
  48693. };
  48694. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  48695. var tm = BABYLON.Tmp.Matrix[0];
  48696. mesh.getWorldMatrix().invertToRef(tm);
  48697. if (this._tmpRay) {
  48698. Ray.TransformToRef(this, tm, this._tmpRay);
  48699. }
  48700. else {
  48701. this._tmpRay = Ray.Transform(this, tm);
  48702. }
  48703. return mesh.intersects(this._tmpRay, fastCheck);
  48704. };
  48705. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  48706. if (results) {
  48707. results.length = 0;
  48708. }
  48709. else {
  48710. results = [];
  48711. }
  48712. for (var i = 0; i < meshes.length; i++) {
  48713. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  48714. if (pickInfo.hit) {
  48715. results.push(pickInfo);
  48716. }
  48717. }
  48718. results.sort(this._comparePickingInfo);
  48719. return results;
  48720. };
  48721. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  48722. if (pickingInfoA.distance < pickingInfoB.distance) {
  48723. return -1;
  48724. }
  48725. else if (pickingInfoA.distance > pickingInfoB.distance) {
  48726. return 1;
  48727. }
  48728. else {
  48729. return 0;
  48730. }
  48731. };
  48732. /**
  48733. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  48734. * @param sega the first point of the segment to test the intersection against
  48735. * @param segb the second point of the segment to test the intersection against
  48736. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  48737. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  48738. */
  48739. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  48740. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  48741. var u = segb.subtract(sega);
  48742. var v = rsegb.subtract(this.origin);
  48743. var w = sega.subtract(this.origin);
  48744. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  48745. var b = BABYLON.Vector3.Dot(u, v);
  48746. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  48747. var d = BABYLON.Vector3.Dot(u, w);
  48748. var e = BABYLON.Vector3.Dot(v, w);
  48749. var D = a * c - b * b; // always >= 0
  48750. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  48751. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  48752. // compute the line parameters of the two closest points
  48753. if (D < Ray.smallnum) {
  48754. sN = 0.0; // force using point P0 on segment S1
  48755. sD = 1.0; // to prevent possible division by 0.0 later
  48756. tN = e;
  48757. tD = c;
  48758. }
  48759. else {
  48760. sN = (b * e - c * d);
  48761. tN = (a * e - b * d);
  48762. if (sN < 0.0) {
  48763. sN = 0.0;
  48764. tN = e;
  48765. tD = c;
  48766. }
  48767. else if (sN > sD) {
  48768. sN = sD;
  48769. tN = e + b;
  48770. tD = c;
  48771. }
  48772. }
  48773. if (tN < 0.0) {
  48774. tN = 0.0;
  48775. // recompute sc for this edge
  48776. if (-d < 0.0) {
  48777. sN = 0.0;
  48778. }
  48779. else if (-d > a)
  48780. sN = sD;
  48781. else {
  48782. sN = -d;
  48783. sD = a;
  48784. }
  48785. }
  48786. else if (tN > tD) {
  48787. tN = tD;
  48788. // recompute sc for this edge
  48789. if ((-d + b) < 0.0) {
  48790. sN = 0;
  48791. }
  48792. else if ((-d + b) > a) {
  48793. sN = sD;
  48794. }
  48795. else {
  48796. sN = (-d + b);
  48797. sD = a;
  48798. }
  48799. }
  48800. // finally do the division to get sc and tc
  48801. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  48802. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  48803. // get the difference of the two closest points
  48804. var qtc = v.multiplyByFloats(tc, tc, tc);
  48805. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  48806. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  48807. if (isIntersected) {
  48808. return qtc.length();
  48809. }
  48810. return -1;
  48811. };
  48812. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  48813. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  48814. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  48815. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  48816. this.direction.normalize();
  48817. return this;
  48818. };
  48819. // Statics
  48820. Ray.Zero = function () {
  48821. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  48822. };
  48823. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  48824. var result = Ray.Zero();
  48825. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  48826. };
  48827. /**
  48828. * 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
  48829. * transformed to the given world matrix.
  48830. * @param origin The origin point
  48831. * @param end The end point
  48832. * @param world a matrix to transform the ray to. Default is the identity matrix.
  48833. */
  48834. Ray.CreateNewFromTo = function (origin, end, world) {
  48835. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  48836. var direction = end.subtract(origin);
  48837. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  48838. direction.normalize();
  48839. return Ray.Transform(new Ray(origin, direction, length), world);
  48840. };
  48841. Ray.Transform = function (ray, matrix) {
  48842. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  48843. Ray.TransformToRef(ray, matrix, result);
  48844. return result;
  48845. };
  48846. Ray.TransformToRef = function (ray, matrix, result) {
  48847. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  48848. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  48849. result.length = ray.length;
  48850. var dir = result.direction;
  48851. var len = dir.length();
  48852. if (!(len === 0 || len === 1)) {
  48853. var num = 1.0 / len;
  48854. dir.x *= num;
  48855. dir.y *= num;
  48856. dir.z *= num;
  48857. result.length *= len;
  48858. }
  48859. };
  48860. Ray.smallnum = 0.00000001;
  48861. Ray.rayl = 10e8;
  48862. return Ray;
  48863. }());
  48864. BABYLON.Ray = Ray;
  48865. })(BABYLON || (BABYLON = {}));
  48866. //# sourceMappingURL=babylon.ray.js.map
  48867. var BABYLON;
  48868. (function (BABYLON) {
  48869. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  48870. if (boxMin.x > sphereCenter.x + sphereRadius)
  48871. return false;
  48872. if (sphereCenter.x - sphereRadius > boxMax.x)
  48873. return false;
  48874. if (boxMin.y > sphereCenter.y + sphereRadius)
  48875. return false;
  48876. if (sphereCenter.y - sphereRadius > boxMax.y)
  48877. return false;
  48878. if (boxMin.z > sphereCenter.z + sphereRadius)
  48879. return false;
  48880. if (sphereCenter.z - sphereRadius > boxMax.z)
  48881. return false;
  48882. return true;
  48883. };
  48884. var getLowestRoot = (function () {
  48885. var result = { root: 0, found: false };
  48886. return function (a, b, c, maxR) {
  48887. result.root = 0;
  48888. result.found = false;
  48889. var determinant = b * b - 4.0 * a * c;
  48890. if (determinant < 0)
  48891. return result;
  48892. var sqrtD = Math.sqrt(determinant);
  48893. var r1 = (-b - sqrtD) / (2.0 * a);
  48894. var r2 = (-b + sqrtD) / (2.0 * a);
  48895. if (r1 > r2) {
  48896. var temp = r2;
  48897. r2 = r1;
  48898. r1 = temp;
  48899. }
  48900. if (r1 > 0 && r1 < maxR) {
  48901. result.root = r1;
  48902. result.found = true;
  48903. return result;
  48904. }
  48905. if (r2 > 0 && r2 < maxR) {
  48906. result.root = r2;
  48907. result.found = true;
  48908. return result;
  48909. }
  48910. return result;
  48911. };
  48912. })();
  48913. var Collider = /** @class */ (function () {
  48914. function Collider() {
  48915. this._collisionPoint = BABYLON.Vector3.Zero();
  48916. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  48917. this._tempVector = BABYLON.Vector3.Zero();
  48918. this._tempVector2 = BABYLON.Vector3.Zero();
  48919. this._tempVector3 = BABYLON.Vector3.Zero();
  48920. this._tempVector4 = BABYLON.Vector3.Zero();
  48921. this._edge = BABYLON.Vector3.Zero();
  48922. this._baseToVertex = BABYLON.Vector3.Zero();
  48923. this._destinationPoint = BABYLON.Vector3.Zero();
  48924. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  48925. this._displacementVector = BABYLON.Vector3.Zero();
  48926. this._radius = BABYLON.Vector3.One();
  48927. this._retry = 0;
  48928. this._basePointWorld = BABYLON.Vector3.Zero();
  48929. this._velocityWorld = BABYLON.Vector3.Zero();
  48930. this._normalizedVelocity = BABYLON.Vector3.Zero();
  48931. this._collisionMask = -1;
  48932. }
  48933. Object.defineProperty(Collider.prototype, "collisionMask", {
  48934. get: function () {
  48935. return this._collisionMask;
  48936. },
  48937. set: function (mask) {
  48938. this._collisionMask = !isNaN(mask) ? mask : -1;
  48939. },
  48940. enumerable: true,
  48941. configurable: true
  48942. });
  48943. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  48944. /**
  48945. * Gets the plane normal used to compute the sliding response (in local space)
  48946. */
  48947. get: function () {
  48948. return this._slidePlaneNormal;
  48949. },
  48950. enumerable: true,
  48951. configurable: true
  48952. });
  48953. // Methods
  48954. Collider.prototype._initialize = function (source, dir, e) {
  48955. this._velocity = dir;
  48956. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  48957. this._basePoint = source;
  48958. source.multiplyToRef(this._radius, this._basePointWorld);
  48959. dir.multiplyToRef(this._radius, this._velocityWorld);
  48960. this._velocityWorldLength = this._velocityWorld.length();
  48961. this._epsilon = e;
  48962. this.collisionFound = false;
  48963. };
  48964. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  48965. pa.subtractToRef(point, this._tempVector);
  48966. pb.subtractToRef(point, this._tempVector2);
  48967. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  48968. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  48969. if (d < 0)
  48970. return false;
  48971. pc.subtractToRef(point, this._tempVector3);
  48972. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  48973. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  48974. if (d < 0)
  48975. return false;
  48976. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  48977. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  48978. return d >= 0;
  48979. };
  48980. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  48981. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  48982. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  48983. if (distance > this._velocityWorldLength + max + sphereRadius) {
  48984. return false;
  48985. }
  48986. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  48987. return false;
  48988. return true;
  48989. };
  48990. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  48991. var t0;
  48992. var embeddedInPlane = false;
  48993. //defensive programming, actually not needed.
  48994. if (!trianglePlaneArray) {
  48995. trianglePlaneArray = [];
  48996. }
  48997. if (!trianglePlaneArray[faceIndex]) {
  48998. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  48999. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  49000. }
  49001. var trianglePlane = trianglePlaneArray[faceIndex];
  49002. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  49003. return;
  49004. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  49005. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  49006. if (normalDotVelocity == 0) {
  49007. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  49008. return;
  49009. embeddedInPlane = true;
  49010. t0 = 0;
  49011. }
  49012. else {
  49013. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49014. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49015. if (t0 > t1) {
  49016. var temp = t1;
  49017. t1 = t0;
  49018. t0 = temp;
  49019. }
  49020. if (t0 > 1.0 || t1 < 0.0)
  49021. return;
  49022. if (t0 < 0)
  49023. t0 = 0;
  49024. if (t0 > 1.0)
  49025. t0 = 1.0;
  49026. }
  49027. this._collisionPoint.copyFromFloats(0, 0, 0);
  49028. var found = false;
  49029. var t = 1.0;
  49030. if (!embeddedInPlane) {
  49031. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  49032. this._velocity.scaleToRef(t0, this._tempVector);
  49033. this._planeIntersectionPoint.addInPlace(this._tempVector);
  49034. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  49035. found = true;
  49036. t = t0;
  49037. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  49038. }
  49039. }
  49040. if (!found) {
  49041. var velocitySquaredLength = this._velocity.lengthSquared();
  49042. var a = velocitySquaredLength;
  49043. this._basePoint.subtractToRef(p1, this._tempVector);
  49044. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49045. var c = this._tempVector.lengthSquared() - 1.0;
  49046. var lowestRoot = getLowestRoot(a, b, c, t);
  49047. if (lowestRoot.found) {
  49048. t = lowestRoot.root;
  49049. found = true;
  49050. this._collisionPoint.copyFrom(p1);
  49051. }
  49052. this._basePoint.subtractToRef(p2, this._tempVector);
  49053. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49054. c = this._tempVector.lengthSquared() - 1.0;
  49055. lowestRoot = getLowestRoot(a, b, c, t);
  49056. if (lowestRoot.found) {
  49057. t = lowestRoot.root;
  49058. found = true;
  49059. this._collisionPoint.copyFrom(p2);
  49060. }
  49061. this._basePoint.subtractToRef(p3, this._tempVector);
  49062. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49063. c = this._tempVector.lengthSquared() - 1.0;
  49064. lowestRoot = getLowestRoot(a, b, c, t);
  49065. if (lowestRoot.found) {
  49066. t = lowestRoot.root;
  49067. found = true;
  49068. this._collisionPoint.copyFrom(p3);
  49069. }
  49070. p2.subtractToRef(p1, this._edge);
  49071. p1.subtractToRef(this._basePoint, this._baseToVertex);
  49072. var edgeSquaredLength = this._edge.lengthSquared();
  49073. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49074. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49075. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49076. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49077. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49078. lowestRoot = getLowestRoot(a, b, c, t);
  49079. if (lowestRoot.found) {
  49080. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49081. if (f >= 0.0 && f <= 1.0) {
  49082. t = lowestRoot.root;
  49083. found = true;
  49084. this._edge.scaleInPlace(f);
  49085. p1.addToRef(this._edge, this._collisionPoint);
  49086. }
  49087. }
  49088. p3.subtractToRef(p2, this._edge);
  49089. p2.subtractToRef(this._basePoint, this._baseToVertex);
  49090. edgeSquaredLength = this._edge.lengthSquared();
  49091. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49092. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49093. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49094. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49095. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49096. lowestRoot = getLowestRoot(a, b, c, t);
  49097. if (lowestRoot.found) {
  49098. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49099. if (f >= 0.0 && f <= 1.0) {
  49100. t = lowestRoot.root;
  49101. found = true;
  49102. this._edge.scaleInPlace(f);
  49103. p2.addToRef(this._edge, this._collisionPoint);
  49104. }
  49105. }
  49106. p1.subtractToRef(p3, this._edge);
  49107. p3.subtractToRef(this._basePoint, this._baseToVertex);
  49108. edgeSquaredLength = this._edge.lengthSquared();
  49109. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49110. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49111. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49112. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49113. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49114. lowestRoot = getLowestRoot(a, b, c, t);
  49115. if (lowestRoot.found) {
  49116. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49117. if (f >= 0.0 && f <= 1.0) {
  49118. t = lowestRoot.root;
  49119. found = true;
  49120. this._edge.scaleInPlace(f);
  49121. p3.addToRef(this._edge, this._collisionPoint);
  49122. }
  49123. }
  49124. }
  49125. if (found) {
  49126. var distToCollision = t * this._velocity.length();
  49127. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  49128. if (!this.intersectionPoint) {
  49129. this.intersectionPoint = this._collisionPoint.clone();
  49130. }
  49131. else {
  49132. this.intersectionPoint.copyFrom(this._collisionPoint);
  49133. }
  49134. this._nearestDistance = distToCollision;
  49135. this.collisionFound = true;
  49136. }
  49137. }
  49138. };
  49139. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  49140. for (var i = indexStart; i < indexEnd; i += 3) {
  49141. var p1 = pts[indices[i] - decal];
  49142. var p2 = pts[indices[i + 1] - decal];
  49143. var p3 = pts[indices[i + 2] - decal];
  49144. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  49145. }
  49146. };
  49147. Collider.prototype._getResponse = function (pos, vel) {
  49148. pos.addToRef(vel, this._destinationPoint);
  49149. vel.scaleInPlace((this._nearestDistance / vel.length()));
  49150. this._basePoint.addToRef(vel, pos);
  49151. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  49152. this._slidePlaneNormal.normalize();
  49153. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  49154. pos.addInPlace(this._displacementVector);
  49155. this.intersectionPoint.addInPlace(this._displacementVector);
  49156. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  49157. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  49158. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  49159. };
  49160. return Collider;
  49161. }());
  49162. BABYLON.Collider = Collider;
  49163. })(BABYLON || (BABYLON = {}));
  49164. //# sourceMappingURL=babylon.collider.js.map
  49165. var BABYLON;
  49166. (function (BABYLON) {
  49167. //WebWorker code will be inserted to this variable.
  49168. BABYLON.CollisionWorker = "";
  49169. var WorkerTaskType;
  49170. (function (WorkerTaskType) {
  49171. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  49172. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  49173. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  49174. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  49175. var WorkerReplyType;
  49176. (function (WorkerReplyType) {
  49177. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  49178. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  49179. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  49180. var CollisionCoordinatorWorker = /** @class */ (function () {
  49181. function CollisionCoordinatorWorker() {
  49182. var _this = this;
  49183. this._scaledPosition = BABYLON.Vector3.Zero();
  49184. this._scaledVelocity = BABYLON.Vector3.Zero();
  49185. this.onMeshUpdated = function (transformNode) {
  49186. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  49187. };
  49188. this.onGeometryUpdated = function (geometry) {
  49189. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  49190. };
  49191. this._afterRender = function () {
  49192. if (!_this._init)
  49193. return;
  49194. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  49195. return;
  49196. }
  49197. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  49198. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  49199. if (_this._runningUpdated > 4) {
  49200. return;
  49201. }
  49202. ++_this._runningUpdated;
  49203. var payload = {
  49204. updatedMeshes: _this._addUpdateMeshesList,
  49205. updatedGeometries: _this._addUpdateGeometriesList,
  49206. removedGeometries: _this._toRemoveGeometryArray,
  49207. removedMeshes: _this._toRemoveMeshesArray
  49208. };
  49209. var message = {
  49210. payload: payload,
  49211. taskType: WorkerTaskType.UPDATE
  49212. };
  49213. var serializable = [];
  49214. for (var id in payload.updatedGeometries) {
  49215. if (payload.updatedGeometries.hasOwnProperty(id)) {
  49216. //prepare transferables
  49217. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  49218. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  49219. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  49220. }
  49221. }
  49222. _this._worker.postMessage(message, serializable);
  49223. _this._addUpdateMeshesList = {};
  49224. _this._addUpdateGeometriesList = {};
  49225. _this._toRemoveGeometryArray = [];
  49226. _this._toRemoveMeshesArray = [];
  49227. };
  49228. this._onMessageFromWorker = function (e) {
  49229. var returnData = e.data;
  49230. if (returnData.error != WorkerReplyType.SUCCESS) {
  49231. //TODO what errors can be returned from the worker?
  49232. BABYLON.Tools.Warn("error returned from worker!");
  49233. return;
  49234. }
  49235. switch (returnData.taskType) {
  49236. case WorkerTaskType.INIT:
  49237. _this._init = true;
  49238. //Update the worked with ALL of the scene's current state
  49239. _this._scene.meshes.forEach(function (mesh) {
  49240. _this.onMeshAdded(mesh);
  49241. });
  49242. _this._scene.getGeometries().forEach(function (geometry) {
  49243. _this.onGeometryAdded(geometry);
  49244. });
  49245. break;
  49246. case WorkerTaskType.UPDATE:
  49247. _this._runningUpdated--;
  49248. break;
  49249. case WorkerTaskType.COLLIDE:
  49250. var returnPayload = returnData.payload;
  49251. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  49252. return;
  49253. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  49254. if (callback) {
  49255. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  49256. if (mesh) {
  49257. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  49258. }
  49259. }
  49260. //cleanup
  49261. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  49262. break;
  49263. }
  49264. };
  49265. this._collisionsCallbackArray = [];
  49266. this._init = false;
  49267. this._runningUpdated = 0;
  49268. this._addUpdateMeshesList = {};
  49269. this._addUpdateGeometriesList = {};
  49270. this._toRemoveGeometryArray = [];
  49271. this._toRemoveMeshesArray = [];
  49272. }
  49273. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  49274. if (!this._init)
  49275. return;
  49276. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  49277. return;
  49278. position.divideToRef(collider._radius, this._scaledPosition);
  49279. displacement.divideToRef(collider._radius, this._scaledVelocity);
  49280. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  49281. var payload = {
  49282. collider: {
  49283. position: this._scaledPosition.asArray(),
  49284. velocity: this._scaledVelocity.asArray(),
  49285. radius: collider._radius.asArray()
  49286. },
  49287. collisionId: collisionIndex,
  49288. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  49289. maximumRetry: maximumRetry
  49290. };
  49291. var message = {
  49292. payload: payload,
  49293. taskType: WorkerTaskType.COLLIDE
  49294. };
  49295. this._worker.postMessage(message);
  49296. };
  49297. CollisionCoordinatorWorker.prototype.init = function (scene) {
  49298. this._scene = scene;
  49299. this._scene.registerAfterRender(this._afterRender);
  49300. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  49301. this._worker = new Worker(workerUrl);
  49302. this._worker.onmessage = this._onMessageFromWorker;
  49303. var message = {
  49304. payload: {},
  49305. taskType: WorkerTaskType.INIT
  49306. };
  49307. this._worker.postMessage(message);
  49308. };
  49309. CollisionCoordinatorWorker.prototype.destroy = function () {
  49310. this._scene.unregisterAfterRender(this._afterRender);
  49311. this._worker.terminate();
  49312. };
  49313. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  49314. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  49315. this.onMeshUpdated(mesh);
  49316. };
  49317. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  49318. this._toRemoveMeshesArray.push(mesh.uniqueId);
  49319. };
  49320. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  49321. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  49322. geometry.onGeometryUpdated = this.onGeometryUpdated;
  49323. this.onGeometryUpdated(geometry);
  49324. };
  49325. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  49326. this._toRemoveGeometryArray.push(geometry.id);
  49327. };
  49328. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  49329. var submeshes = [];
  49330. if (mesh.subMeshes) {
  49331. submeshes = mesh.subMeshes.map(function (sm, idx) {
  49332. var boundingInfo = sm.getBoundingInfo();
  49333. return {
  49334. position: idx,
  49335. verticesStart: sm.verticesStart,
  49336. verticesCount: sm.verticesCount,
  49337. indexStart: sm.indexStart,
  49338. indexCount: sm.indexCount,
  49339. hasMaterial: !!sm.getMaterial(),
  49340. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49341. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49342. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49343. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  49344. };
  49345. });
  49346. }
  49347. var geometryId = null;
  49348. if (mesh instanceof BABYLON.Mesh) {
  49349. var geometry = mesh.geometry;
  49350. geometryId = geometry ? geometry.id : null;
  49351. }
  49352. else if (mesh instanceof BABYLON.InstancedMesh) {
  49353. var geometry = mesh.sourceMesh.geometry;
  49354. geometryId = geometry ? geometry.id : null;
  49355. }
  49356. var boundingInfo = mesh.getBoundingInfo();
  49357. return {
  49358. uniqueId: mesh.uniqueId,
  49359. id: mesh.id,
  49360. name: mesh.name,
  49361. geometryId: geometryId,
  49362. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49363. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49364. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49365. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  49366. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  49367. subMeshes: submeshes,
  49368. checkCollisions: mesh.checkCollisions
  49369. };
  49370. };
  49371. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  49372. return {
  49373. id: geometry.id,
  49374. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  49375. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  49376. indices: new Uint32Array(geometry.getIndices() || []),
  49377. };
  49378. };
  49379. return CollisionCoordinatorWorker;
  49380. }());
  49381. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  49382. var CollisionCoordinatorLegacy = /** @class */ (function () {
  49383. function CollisionCoordinatorLegacy() {
  49384. this._scaledPosition = BABYLON.Vector3.Zero();
  49385. this._scaledVelocity = BABYLON.Vector3.Zero();
  49386. this._finalPosition = BABYLON.Vector3.Zero();
  49387. }
  49388. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  49389. position.divideToRef(collider._radius, this._scaledPosition);
  49390. displacement.divideToRef(collider._radius, this._scaledVelocity);
  49391. collider.collidedMesh = null;
  49392. collider._retry = 0;
  49393. collider._initialVelocity = this._scaledVelocity;
  49394. collider._initialPosition = this._scaledPosition;
  49395. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  49396. this._finalPosition.multiplyInPlace(collider._radius);
  49397. //run the callback
  49398. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  49399. };
  49400. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  49401. this._scene = scene;
  49402. };
  49403. CollisionCoordinatorLegacy.prototype.destroy = function () {
  49404. //Legacy need no destruction method.
  49405. };
  49406. //No update in legacy mode
  49407. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  49408. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  49409. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  49410. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  49411. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  49412. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  49413. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  49414. if (excludedMesh === void 0) { excludedMesh = null; }
  49415. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  49416. if (collider._retry >= maximumRetry) {
  49417. finalPosition.copyFrom(position);
  49418. return;
  49419. }
  49420. // Check if this is a mesh else camera or -1
  49421. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  49422. collider._initialize(position, velocity, closeDistance);
  49423. // Check all meshes
  49424. for (var index = 0; index < this._scene.meshes.length; index++) {
  49425. var mesh = this._scene.meshes[index];
  49426. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  49427. mesh._checkCollision(collider);
  49428. }
  49429. }
  49430. if (!collider.collisionFound) {
  49431. position.addToRef(velocity, finalPosition);
  49432. return;
  49433. }
  49434. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  49435. collider._getResponse(position, velocity);
  49436. }
  49437. if (velocity.length() <= closeDistance) {
  49438. finalPosition.copyFrom(position);
  49439. return;
  49440. }
  49441. collider._retry++;
  49442. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  49443. };
  49444. return CollisionCoordinatorLegacy;
  49445. }());
  49446. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  49447. })(BABYLON || (BABYLON = {}));
  49448. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  49449. var BABYLON;
  49450. (function (BABYLON) {
  49451. /**
  49452. * A particle represents one of the element emitted by a particle system.
  49453. * This is mainly define by its coordinates, direction, velocity and age.
  49454. */
  49455. var Particle = /** @class */ (function () {
  49456. /**
  49457. * Creates a new instance of @see Particle
  49458. * @param particleSystem the particle system the particle belongs to
  49459. */
  49460. function Particle(particleSystem) {
  49461. this.particleSystem = particleSystem;
  49462. /**
  49463. * The world position of the particle in the scene.
  49464. */
  49465. this.position = BABYLON.Vector3.Zero();
  49466. /**
  49467. * The world direction of the particle in the scene.
  49468. */
  49469. this.direction = BABYLON.Vector3.Zero();
  49470. /**
  49471. * The color of the particle.
  49472. */
  49473. this.color = new BABYLON.Color4(0, 0, 0, 0);
  49474. /**
  49475. * The color change of the particle per step.
  49476. */
  49477. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  49478. /**
  49479. * Defines how long will the life of the particle be.
  49480. */
  49481. this.lifeTime = 1.0;
  49482. /**
  49483. * The current age of the particle.
  49484. */
  49485. this.age = 0;
  49486. /**
  49487. * The current size of the particle.
  49488. */
  49489. this.size = 0;
  49490. /**
  49491. * The current angle of the particle.
  49492. */
  49493. this.angle = 0;
  49494. /**
  49495. * Defines how fast is the angle changing.
  49496. */
  49497. this.angularSpeed = 0;
  49498. /**
  49499. * Defines the cell index used by the particle to be rendered from a sprite.
  49500. */
  49501. this.cellIndex = 0;
  49502. this._currentFrameCounter = 0;
  49503. if (!this.particleSystem.isAnimationSheetEnabled) {
  49504. return;
  49505. }
  49506. this.cellIndex = this.particleSystem.startSpriteCellID;
  49507. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  49508. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  49509. }
  49510. else {
  49511. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  49512. }
  49513. }
  49514. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  49515. // (ageOffset / scaledUpdateSpeed) / available cells
  49516. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  49517. this._currentFrameCounter += scaledUpdateSpeed;
  49518. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  49519. this._currentFrameCounter = 0;
  49520. this.cellIndex++;
  49521. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  49522. this.cellIndex = this.particleSystem.endSpriteCellID;
  49523. }
  49524. }
  49525. };
  49526. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  49527. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  49528. this.cellIndex++;
  49529. this._currentFrameCounter = 0;
  49530. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  49531. if (this.particleSystem.spriteCellLoop) {
  49532. this.cellIndex = this.particleSystem.startSpriteCellID;
  49533. }
  49534. else {
  49535. this.cellIndex = this.particleSystem.endSpriteCellID;
  49536. }
  49537. }
  49538. }
  49539. else {
  49540. this._currentFrameCounter++;
  49541. }
  49542. };
  49543. /**
  49544. * Copy the properties of particle to another one.
  49545. * @param other the particle to copy the information to.
  49546. */
  49547. Particle.prototype.copyTo = function (other) {
  49548. other.position.copyFrom(this.position);
  49549. other.direction.copyFrom(this.direction);
  49550. other.color.copyFrom(this.color);
  49551. other.colorStep.copyFrom(this.colorStep);
  49552. other.lifeTime = this.lifeTime;
  49553. other.age = this.age;
  49554. other.size = this.size;
  49555. other.angle = this.angle;
  49556. other.angularSpeed = this.angularSpeed;
  49557. other.particleSystem = this.particleSystem;
  49558. other.cellIndex = this.cellIndex;
  49559. };
  49560. return Particle;
  49561. }());
  49562. BABYLON.Particle = Particle;
  49563. })(BABYLON || (BABYLON = {}));
  49564. //# sourceMappingURL=babylon.particle.js.map
  49565. var BABYLON;
  49566. (function (BABYLON) {
  49567. /**
  49568. * This represents a particle system in Babylon.
  49569. * 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.
  49570. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  49571. * @example https://doc.babylonjs.com/babylon101/particles
  49572. */
  49573. var ParticleSystem = /** @class */ (function () {
  49574. /**
  49575. * Instantiates a particle system.
  49576. * 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.
  49577. * @param name The name of the particle system
  49578. * @param capacity The max number of particles alive at the same time
  49579. * @param scene The scene the particle system belongs to
  49580. * @param customEffect a custom effect used to change the way particles are rendered by default
  49581. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  49582. * @param epsilon Offset used to render the particles
  49583. */
  49584. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  49585. if (customEffect === void 0) { customEffect = null; }
  49586. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  49587. if (epsilon === void 0) { epsilon = 0.01; }
  49588. var _this = this;
  49589. /**
  49590. * List of animations used by the particle system.
  49591. */
  49592. this.animations = [];
  49593. /**
  49594. * The rendering group used by the Particle system to chose when to render.
  49595. */
  49596. this.renderingGroupId = 0;
  49597. /**
  49598. * The emitter represents the Mesh or position we are attaching the particle system to.
  49599. */
  49600. this.emitter = null;
  49601. /**
  49602. * The density of particles, the rate of particle flow
  49603. */
  49604. this.emitRate = 10;
  49605. /**
  49606. * If you want to launch only a few particles at once, that can be done, as well.
  49607. */
  49608. this.manualEmitCount = -1;
  49609. /**
  49610. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  49611. */
  49612. this.updateSpeed = 0.01;
  49613. /**
  49614. * The amount of time the particle system is running (depends of the overall speed above).
  49615. */
  49616. this.targetStopDuration = 0;
  49617. /**
  49618. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  49619. */
  49620. this.disposeOnStop = false;
  49621. /**
  49622. * Minimum power of emitting particles.
  49623. */
  49624. this.minEmitPower = 1;
  49625. /**
  49626. * Maximum power of emitting particles.
  49627. */
  49628. this.maxEmitPower = 1;
  49629. /**
  49630. * Minimum life time of emitting particles.
  49631. */
  49632. this.minLifeTime = 1;
  49633. /**
  49634. * Maximum life time of emitting particles.
  49635. */
  49636. this.maxLifeTime = 1;
  49637. /**
  49638. * Minimum Size of emitting particles.
  49639. */
  49640. this.minSize = 1;
  49641. /**
  49642. * Maximum Size of emitting particles.
  49643. */
  49644. this.maxSize = 1;
  49645. /**
  49646. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  49647. */
  49648. this.minAngularSpeed = 0;
  49649. /**
  49650. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  49651. */
  49652. this.maxAngularSpeed = 0;
  49653. /**
  49654. * The layer mask we are rendering the particles through.
  49655. */
  49656. this.layerMask = 0x0FFFFFFF;
  49657. /**
  49658. * This can help using your own shader to render the particle system.
  49659. * The according effect will be created
  49660. */
  49661. this.customShader = null;
  49662. /**
  49663. * By default particle system starts as soon as they are created. This prevents the
  49664. * automatic start to happen and let you decide when to start emitting particles.
  49665. */
  49666. this.preventAutoStart = false;
  49667. /**
  49668. * Callback triggered when the particle animation is ending.
  49669. */
  49670. this.onAnimationEnd = null;
  49671. /**
  49672. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  49673. */
  49674. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  49675. /**
  49676. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  49677. * to override the particles.
  49678. */
  49679. this.forceDepthWrite = false;
  49680. /**
  49681. * You can use gravity if you want to give an orientation to your particles.
  49682. */
  49683. this.gravity = BABYLON.Vector3.Zero();
  49684. /**
  49685. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49686. */
  49687. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  49688. /**
  49689. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49690. */
  49691. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  49692. /**
  49693. * 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.
  49694. */
  49695. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  49696. /**
  49697. * 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.
  49698. */
  49699. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  49700. /**
  49701. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  49702. */
  49703. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49704. /**
  49705. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  49706. */
  49707. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49708. /**
  49709. * Color the particle will have at the end of its lifetime.
  49710. */
  49711. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  49712. /**
  49713. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  49714. */
  49715. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49716. /**
  49717. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  49718. */
  49719. this.spriteCellLoop = true;
  49720. /**
  49721. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  49722. */
  49723. this.spriteCellChangeSpeed = 0;
  49724. /**
  49725. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  49726. */
  49727. this.startSpriteCellID = 0;
  49728. /**
  49729. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  49730. */
  49731. this.endSpriteCellID = 0;
  49732. /**
  49733. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  49734. */
  49735. this.spriteCellWidth = 0;
  49736. /**
  49737. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  49738. */
  49739. this.spriteCellHeight = 0;
  49740. /**
  49741. * An event triggered when the system is disposed.
  49742. */
  49743. this.onDisposeObservable = new BABYLON.Observable();
  49744. this._particles = new Array();
  49745. this._stockParticles = new Array();
  49746. this._newPartsExcess = 0;
  49747. this._vertexBuffers = {};
  49748. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  49749. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  49750. this._scaledDirection = BABYLON.Vector3.Zero();
  49751. this._scaledGravity = BABYLON.Vector3.Zero();
  49752. this._currentRenderId = -1;
  49753. this._started = false;
  49754. this._stopped = false;
  49755. this._actualFrame = 0;
  49756. this._vertexBufferSize = 11;
  49757. this._appendParticleVertexes = null;
  49758. this.id = name;
  49759. this.name = name;
  49760. this._capacity = capacity;
  49761. this._epsilon = epsilon;
  49762. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  49763. if (isAnimationSheetEnabled) {
  49764. this._vertexBufferSize = 12;
  49765. }
  49766. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  49767. this._customEffect = customEffect;
  49768. scene.particleSystems.push(this);
  49769. this._createIndexBuffer();
  49770. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  49771. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  49772. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  49773. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  49774. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  49775. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  49776. if (this._isAnimationSheetEnabled) {
  49777. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  49778. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  49779. }
  49780. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  49781. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  49782. this._vertexBuffers["options"] = options;
  49783. // Default behaviors
  49784. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  49785. this.updateFunction = function (particles) {
  49786. for (var index = 0; index < particles.length; index++) {
  49787. var particle = particles[index];
  49788. particle.age += _this._scaledUpdateSpeed;
  49789. if (particle.age >= particle.lifeTime) {
  49790. _this.recycleParticle(particle);
  49791. index--;
  49792. continue;
  49793. }
  49794. else {
  49795. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  49796. particle.color.addInPlace(_this._scaledColorStep);
  49797. if (particle.color.a < 0)
  49798. particle.color.a = 0;
  49799. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  49800. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  49801. particle.position.addInPlace(_this._scaledDirection);
  49802. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  49803. particle.direction.addInPlace(_this._scaledGravity);
  49804. if (_this._isAnimationSheetEnabled) {
  49805. particle.updateCellIndex(_this._scaledUpdateSpeed);
  49806. }
  49807. }
  49808. }
  49809. };
  49810. }
  49811. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  49812. /**
  49813. * Sets a callback that will be triggered when the system is disposed.
  49814. */
  49815. set: function (callback) {
  49816. if (this._onDisposeObserver) {
  49817. this.onDisposeObservable.remove(this._onDisposeObserver);
  49818. }
  49819. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  49820. },
  49821. enumerable: true,
  49822. configurable: true
  49823. });
  49824. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  49825. /**
  49826. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  49827. */
  49828. get: function () {
  49829. return this._isAnimationSheetEnabled;
  49830. },
  49831. enumerable: true,
  49832. configurable: true
  49833. });
  49834. ParticleSystem.prototype._createIndexBuffer = function () {
  49835. var indices = [];
  49836. var index = 0;
  49837. for (var count = 0; count < this._capacity; count++) {
  49838. indices.push(index);
  49839. indices.push(index + 1);
  49840. indices.push(index + 2);
  49841. indices.push(index);
  49842. indices.push(index + 2);
  49843. indices.push(index + 3);
  49844. index += 4;
  49845. }
  49846. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  49847. };
  49848. /**
  49849. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  49850. * Its lifetime will start back at 0.
  49851. * @param particle The particle to recycle
  49852. */
  49853. ParticleSystem.prototype.recycleParticle = function (particle) {
  49854. var lastParticle = this._particles.pop();
  49855. if (lastParticle !== particle) {
  49856. lastParticle.copyTo(particle);
  49857. this._stockParticles.push(lastParticle);
  49858. }
  49859. };
  49860. /**
  49861. * Gets the maximum number of particles active at the same time.
  49862. * @returns The max number of active particles.
  49863. */
  49864. ParticleSystem.prototype.getCapacity = function () {
  49865. return this._capacity;
  49866. };
  49867. /**
  49868. * Gets Wether there are still active particles in the system.
  49869. * @returns True if it is alive, otherwise false.
  49870. */
  49871. ParticleSystem.prototype.isAlive = function () {
  49872. return this._alive;
  49873. };
  49874. /**
  49875. * Gets Wether the system has been started.
  49876. * @returns True if it has been started, otherwise false.
  49877. */
  49878. ParticleSystem.prototype.isStarted = function () {
  49879. return this._started;
  49880. };
  49881. /**
  49882. * Starts the particle system and begins to emit.
  49883. */
  49884. ParticleSystem.prototype.start = function () {
  49885. this._started = true;
  49886. this._stopped = false;
  49887. this._actualFrame = 0;
  49888. };
  49889. /**
  49890. * Stops the particle system.
  49891. */
  49892. ParticleSystem.prototype.stop = function () {
  49893. this._stopped = true;
  49894. };
  49895. /**
  49896. * @ignore (for internal use only)
  49897. */
  49898. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  49899. var offset = index * this._vertexBufferSize;
  49900. this._vertexData[offset] = particle.position.x;
  49901. this._vertexData[offset + 1] = particle.position.y;
  49902. this._vertexData[offset + 2] = particle.position.z;
  49903. this._vertexData[offset + 3] = particle.color.r;
  49904. this._vertexData[offset + 4] = particle.color.g;
  49905. this._vertexData[offset + 5] = particle.color.b;
  49906. this._vertexData[offset + 6] = particle.color.a;
  49907. this._vertexData[offset + 7] = particle.angle;
  49908. this._vertexData[offset + 8] = particle.size;
  49909. this._vertexData[offset + 9] = offsetX;
  49910. this._vertexData[offset + 10] = offsetY;
  49911. };
  49912. /**
  49913. * @ignore (for internal use only)
  49914. */
  49915. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  49916. if (offsetX === 0)
  49917. offsetX = this._epsilon;
  49918. else if (offsetX === 1)
  49919. offsetX = 1 - this._epsilon;
  49920. if (offsetY === 0)
  49921. offsetY = this._epsilon;
  49922. else if (offsetY === 1)
  49923. offsetY = 1 - this._epsilon;
  49924. var offset = index * this._vertexBufferSize;
  49925. this._vertexData[offset] = particle.position.x;
  49926. this._vertexData[offset + 1] = particle.position.y;
  49927. this._vertexData[offset + 2] = particle.position.z;
  49928. this._vertexData[offset + 3] = particle.color.r;
  49929. this._vertexData[offset + 4] = particle.color.g;
  49930. this._vertexData[offset + 5] = particle.color.b;
  49931. this._vertexData[offset + 6] = particle.color.a;
  49932. this._vertexData[offset + 7] = particle.angle;
  49933. this._vertexData[offset + 8] = particle.size;
  49934. this._vertexData[offset + 9] = offsetX;
  49935. this._vertexData[offset + 10] = offsetY;
  49936. this._vertexData[offset + 11] = particle.cellIndex;
  49937. };
  49938. ParticleSystem.prototype._update = function (newParticles) {
  49939. // Update current
  49940. this._alive = this._particles.length > 0;
  49941. this.updateFunction(this._particles);
  49942. // Add new ones
  49943. var worldMatrix;
  49944. if (this.emitter.position) {
  49945. var emitterMesh = this.emitter;
  49946. worldMatrix = emitterMesh.getWorldMatrix();
  49947. }
  49948. else {
  49949. var emitterPosition = this.emitter;
  49950. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  49951. }
  49952. var particle;
  49953. for (var index = 0; index < newParticles; index++) {
  49954. if (this._particles.length === this._capacity) {
  49955. break;
  49956. }
  49957. if (this._stockParticles.length !== 0) {
  49958. particle = this._stockParticles.pop();
  49959. particle.age = 0;
  49960. particle.cellIndex = this.startSpriteCellID;
  49961. }
  49962. else {
  49963. particle = new BABYLON.Particle(this);
  49964. }
  49965. this._particles.push(particle);
  49966. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  49967. if (this.startPositionFunction) {
  49968. this.startPositionFunction(worldMatrix, particle.position, particle);
  49969. }
  49970. else {
  49971. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  49972. }
  49973. if (this.startDirectionFunction) {
  49974. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  49975. }
  49976. else {
  49977. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  49978. }
  49979. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  49980. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  49981. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  49982. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  49983. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  49984. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  49985. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  49986. }
  49987. };
  49988. ParticleSystem.prototype._getEffect = function () {
  49989. if (this._customEffect) {
  49990. return this._customEffect;
  49991. }
  49992. ;
  49993. var defines = [];
  49994. if (this._scene.clipPlane) {
  49995. defines.push("#define CLIPPLANE");
  49996. }
  49997. if (this._isAnimationSheetEnabled) {
  49998. defines.push("#define ANIMATESHEET");
  49999. }
  50000. // Effect
  50001. var join = defines.join("\n");
  50002. if (this._cachedDefines !== join) {
  50003. this._cachedDefines = join;
  50004. var attributesNamesOrOptions;
  50005. var effectCreationOption;
  50006. if (this._isAnimationSheetEnabled) {
  50007. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  50008. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  50009. }
  50010. else {
  50011. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  50012. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  50013. }
  50014. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  50015. }
  50016. return this._effect;
  50017. };
  50018. /**
  50019. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  50020. */
  50021. ParticleSystem.prototype.animate = function () {
  50022. if (!this._started)
  50023. return;
  50024. var effect = this._getEffect();
  50025. // Check
  50026. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  50027. return;
  50028. if (this._currentRenderId === this._scene.getRenderId()) {
  50029. return;
  50030. }
  50031. this._currentRenderId = this._scene.getRenderId();
  50032. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  50033. // determine the number of particles we need to create
  50034. var newParticles;
  50035. if (this.manualEmitCount > -1) {
  50036. newParticles = this.manualEmitCount;
  50037. this._newPartsExcess = 0;
  50038. this.manualEmitCount = 0;
  50039. }
  50040. else {
  50041. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  50042. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  50043. }
  50044. if (this._newPartsExcess > 1.0) {
  50045. newParticles += this._newPartsExcess >> 0;
  50046. this._newPartsExcess -= this._newPartsExcess >> 0;
  50047. }
  50048. this._alive = false;
  50049. if (!this._stopped) {
  50050. this._actualFrame += this._scaledUpdateSpeed;
  50051. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  50052. this.stop();
  50053. }
  50054. else {
  50055. newParticles = 0;
  50056. }
  50057. this._update(newParticles);
  50058. // Stopped?
  50059. if (this._stopped) {
  50060. if (!this._alive) {
  50061. this._started = false;
  50062. if (this.onAnimationEnd) {
  50063. this.onAnimationEnd();
  50064. }
  50065. if (this.disposeOnStop) {
  50066. this._scene._toBeDisposed.push(this);
  50067. }
  50068. }
  50069. }
  50070. // Animation sheet
  50071. if (this._isAnimationSheetEnabled) {
  50072. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  50073. }
  50074. else {
  50075. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  50076. }
  50077. // Update VBO
  50078. var offset = 0;
  50079. for (var index = 0; index < this._particles.length; index++) {
  50080. var particle = this._particles[index];
  50081. this._appendParticleVertexes(offset, particle);
  50082. offset += 4;
  50083. }
  50084. if (this._vertexBuffer) {
  50085. this._vertexBuffer.update(this._vertexData);
  50086. }
  50087. };
  50088. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  50089. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  50090. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  50091. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  50092. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  50093. };
  50094. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  50095. this._appendParticleVertex(offset++, particle, 0, 0);
  50096. this._appendParticleVertex(offset++, particle, 1, 0);
  50097. this._appendParticleVertex(offset++, particle, 1, 1);
  50098. this._appendParticleVertex(offset++, particle, 0, 1);
  50099. };
  50100. /**
  50101. * Rebuilds the particle system.
  50102. */
  50103. ParticleSystem.prototype.rebuild = function () {
  50104. this._createIndexBuffer();
  50105. if (this._vertexBuffer) {
  50106. this._vertexBuffer._rebuild();
  50107. }
  50108. };
  50109. /**
  50110. * Renders the particle system in its current state.
  50111. * @returns the current number of particles.
  50112. */
  50113. ParticleSystem.prototype.render = function () {
  50114. var effect = this._getEffect();
  50115. // Check
  50116. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length)
  50117. return 0;
  50118. var engine = this._scene.getEngine();
  50119. // Render
  50120. engine.enableEffect(effect);
  50121. engine.setState(false);
  50122. var viewMatrix = this._scene.getViewMatrix();
  50123. effect.setTexture("diffuseSampler", this.particleTexture);
  50124. effect.setMatrix("view", viewMatrix);
  50125. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50126. if (this._isAnimationSheetEnabled) {
  50127. var baseSize = this.particleTexture.getBaseSize();
  50128. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  50129. }
  50130. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  50131. if (this._scene.clipPlane) {
  50132. var clipPlane = this._scene.clipPlane;
  50133. var invView = viewMatrix.clone();
  50134. invView.invert();
  50135. effect.setMatrix("invView", invView);
  50136. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  50137. }
  50138. // VBOs
  50139. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50140. // Draw order
  50141. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  50142. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  50143. }
  50144. else {
  50145. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50146. }
  50147. if (this.forceDepthWrite) {
  50148. engine.setDepthWrite(true);
  50149. }
  50150. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  50151. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50152. return this._particles.length;
  50153. };
  50154. /**
  50155. * Disposes the particle system and free the associated resources.
  50156. */
  50157. ParticleSystem.prototype.dispose = function () {
  50158. if (this._vertexBuffer) {
  50159. this._vertexBuffer.dispose();
  50160. this._vertexBuffer = null;
  50161. }
  50162. if (this._indexBuffer) {
  50163. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50164. this._indexBuffer = null;
  50165. }
  50166. if (this.particleTexture) {
  50167. this.particleTexture.dispose();
  50168. this.particleTexture = null;
  50169. }
  50170. // Remove from scene
  50171. var index = this._scene.particleSystems.indexOf(this);
  50172. if (index > -1) {
  50173. this._scene.particleSystems.splice(index, 1);
  50174. }
  50175. // Callback
  50176. this.onDisposeObservable.notifyObservers(this);
  50177. this.onDisposeObservable.clear();
  50178. };
  50179. /**
  50180. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  50181. * @param radius The radius of the sphere to emit from
  50182. * @returns the emitter
  50183. */
  50184. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  50185. if (radius === void 0) { radius = 1; }
  50186. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  50187. this.particleEmitterType = particleEmitter;
  50188. return particleEmitter;
  50189. };
  50190. /**
  50191. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  50192. * @param radius The radius of the sphere to emit from
  50193. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  50194. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  50195. * @returns the emitter
  50196. */
  50197. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  50198. if (radius === void 0) { radius = 1; }
  50199. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  50200. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  50201. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  50202. this.particleEmitterType = particleEmitter;
  50203. return particleEmitter;
  50204. };
  50205. /**
  50206. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  50207. * @param radius The radius of the cone to emit from
  50208. * @param angle The base angle of the cone
  50209. * @returns the emitter
  50210. */
  50211. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  50212. if (radius === void 0) { radius = 1; }
  50213. if (angle === void 0) { angle = Math.PI / 4; }
  50214. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  50215. this.particleEmitterType = particleEmitter;
  50216. return particleEmitter;
  50217. };
  50218. // 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.
  50219. /**
  50220. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  50221. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  50222. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  50223. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50224. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50225. * @returns the emitter
  50226. */
  50227. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  50228. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  50229. this.direction1 = direction1;
  50230. this.direction2 = direction2;
  50231. this.minEmitBox = minEmitBox;
  50232. this.maxEmitBox = maxEmitBox;
  50233. this.particleEmitterType = particleEmitter;
  50234. return particleEmitter;
  50235. };
  50236. /**
  50237. * Clones the particle system.
  50238. * @param name The name of the cloned object
  50239. * @param newEmitter The new emitter to use
  50240. * @returns the cloned particle system
  50241. */
  50242. ParticleSystem.prototype.clone = function (name, newEmitter) {
  50243. var custom = null;
  50244. var program = null;
  50245. if (this.customShader != null) {
  50246. program = this.customShader;
  50247. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50248. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50249. }
  50250. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  50251. result.customShader = program;
  50252. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  50253. if (newEmitter === undefined) {
  50254. newEmitter = this.emitter;
  50255. }
  50256. result.emitter = newEmitter;
  50257. if (this.particleTexture) {
  50258. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  50259. }
  50260. if (!this.preventAutoStart) {
  50261. result.start();
  50262. }
  50263. return result;
  50264. };
  50265. /**
  50266. * Serializes the particle system to a JSON object.
  50267. * @returns the JSON object
  50268. */
  50269. ParticleSystem.prototype.serialize = function () {
  50270. var serializationObject = {};
  50271. serializationObject.name = this.name;
  50272. serializationObject.id = this.id;
  50273. // Emitter
  50274. if (this.emitter.position) {
  50275. var emitterMesh = this.emitter;
  50276. serializationObject.emitterId = emitterMesh.id;
  50277. }
  50278. else {
  50279. var emitterPosition = this.emitter;
  50280. serializationObject.emitter = emitterPosition.asArray();
  50281. }
  50282. serializationObject.capacity = this.getCapacity();
  50283. if (this.particleTexture) {
  50284. serializationObject.textureName = this.particleTexture.name;
  50285. }
  50286. // Animations
  50287. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  50288. // Particle system
  50289. serializationObject.minAngularSpeed = this.minAngularSpeed;
  50290. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  50291. serializationObject.minSize = this.minSize;
  50292. serializationObject.maxSize = this.maxSize;
  50293. serializationObject.minEmitPower = this.minEmitPower;
  50294. serializationObject.maxEmitPower = this.maxEmitPower;
  50295. serializationObject.minLifeTime = this.minLifeTime;
  50296. serializationObject.maxLifeTime = this.maxLifeTime;
  50297. serializationObject.emitRate = this.emitRate;
  50298. serializationObject.minEmitBox = this.minEmitBox.asArray();
  50299. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  50300. serializationObject.gravity = this.gravity.asArray();
  50301. serializationObject.direction1 = this.direction1.asArray();
  50302. serializationObject.direction2 = this.direction2.asArray();
  50303. serializationObject.color1 = this.color1.asArray();
  50304. serializationObject.color2 = this.color2.asArray();
  50305. serializationObject.colorDead = this.colorDead.asArray();
  50306. serializationObject.updateSpeed = this.updateSpeed;
  50307. serializationObject.targetStopDuration = this.targetStopDuration;
  50308. serializationObject.textureMask = this.textureMask.asArray();
  50309. serializationObject.blendMode = this.blendMode;
  50310. serializationObject.customShader = this.customShader;
  50311. serializationObject.preventAutoStart = this.preventAutoStart;
  50312. serializationObject.startSpriteCellID = this.startSpriteCellID;
  50313. serializationObject.endSpriteCellID = this.endSpriteCellID;
  50314. serializationObject.spriteCellLoop = this.spriteCellLoop;
  50315. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  50316. serializationObject.spriteCellWidth = this.spriteCellWidth;
  50317. serializationObject.spriteCellHeight = this.spriteCellHeight;
  50318. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  50319. return serializationObject;
  50320. };
  50321. /**
  50322. * Parses a JSON object to create a particle system.
  50323. * @param parsedParticleSystem The JSON object to parse
  50324. * @param scene The scene to create the particle system in
  50325. * @param rootUrl The root url to use to load external dependencies like texture
  50326. * @returns the Parsed particle system
  50327. */
  50328. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  50329. var name = parsedParticleSystem.name;
  50330. var custom = null;
  50331. var program = null;
  50332. if (parsedParticleSystem.customShader) {
  50333. program = parsedParticleSystem.customShader;
  50334. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50335. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50336. }
  50337. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  50338. particleSystem.customShader = program;
  50339. if (parsedParticleSystem.id) {
  50340. particleSystem.id = parsedParticleSystem.id;
  50341. }
  50342. // Auto start
  50343. if (parsedParticleSystem.preventAutoStart) {
  50344. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  50345. }
  50346. // Texture
  50347. if (parsedParticleSystem.textureName) {
  50348. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  50349. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  50350. }
  50351. // Emitter
  50352. if (parsedParticleSystem.emitterId) {
  50353. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  50354. }
  50355. else {
  50356. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  50357. }
  50358. // Animations
  50359. if (parsedParticleSystem.animations) {
  50360. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  50361. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  50362. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  50363. }
  50364. }
  50365. if (parsedParticleSystem.autoAnimate) {
  50366. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  50367. }
  50368. // Particle system
  50369. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  50370. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  50371. particleSystem.minSize = parsedParticleSystem.minSize;
  50372. particleSystem.maxSize = parsedParticleSystem.maxSize;
  50373. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  50374. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  50375. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  50376. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  50377. particleSystem.emitRate = parsedParticleSystem.emitRate;
  50378. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  50379. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  50380. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  50381. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  50382. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  50383. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  50384. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  50385. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  50386. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  50387. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  50388. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  50389. particleSystem.blendMode = parsedParticleSystem.blendMode;
  50390. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  50391. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  50392. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  50393. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  50394. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  50395. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  50396. if (!particleSystem.preventAutoStart) {
  50397. particleSystem.start();
  50398. }
  50399. return particleSystem;
  50400. };
  50401. /**
  50402. * Source color is added to the destination color without alpha affecting the result.
  50403. */
  50404. ParticleSystem.BLENDMODE_ONEONE = 0;
  50405. /**
  50406. * Blend current color and particle color using particle’s alpha.
  50407. */
  50408. ParticleSystem.BLENDMODE_STANDARD = 1;
  50409. return ParticleSystem;
  50410. }());
  50411. BABYLON.ParticleSystem = ParticleSystem;
  50412. })(BABYLON || (BABYLON = {}));
  50413. //# sourceMappingURL=babylon.particleSystem.js.map
  50414. var BABYLON;
  50415. (function (BABYLON) {
  50416. /**
  50417. * Particle emitter emitting particles from the inside of a box.
  50418. * It emits the particles randomly between 2 given directions.
  50419. */
  50420. var BoxParticleEmitter = /** @class */ (function () {
  50421. // to be updated like the rest of emitters when breaking changes.
  50422. // all property should be come public variables and passed through constructor.
  50423. /**
  50424. * Creates a new instance of @see BoxParticleEmitter
  50425. * @param _particleSystem the particle system associated with the emitter
  50426. */
  50427. function BoxParticleEmitter(_particleSystem) {
  50428. this._particleSystem = _particleSystem;
  50429. }
  50430. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  50431. /**
  50432. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50433. */
  50434. get: function () {
  50435. return this._particleSystem.direction1;
  50436. },
  50437. /**
  50438. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50439. */
  50440. set: function (value) {
  50441. this._particleSystem.direction1 = value;
  50442. },
  50443. enumerable: true,
  50444. configurable: true
  50445. });
  50446. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  50447. /**
  50448. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50449. */
  50450. get: function () {
  50451. return this._particleSystem.direction2;
  50452. },
  50453. /**
  50454. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50455. */
  50456. set: function (value) {
  50457. this._particleSystem.direction2 = value;
  50458. },
  50459. enumerable: true,
  50460. configurable: true
  50461. });
  50462. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  50463. /**
  50464. * 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.
  50465. */
  50466. get: function () {
  50467. return this._particleSystem.minEmitBox;
  50468. },
  50469. /**
  50470. * 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.
  50471. */
  50472. set: function (value) {
  50473. this._particleSystem.minEmitBox = value;
  50474. },
  50475. enumerable: true,
  50476. configurable: true
  50477. });
  50478. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  50479. /**
  50480. * 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.
  50481. */
  50482. get: function () {
  50483. return this._particleSystem.maxEmitBox;
  50484. },
  50485. /**
  50486. * 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.
  50487. */
  50488. set: function (value) {
  50489. this._particleSystem.maxEmitBox = value;
  50490. },
  50491. enumerable: true,
  50492. configurable: true
  50493. });
  50494. /**
  50495. * Called by the particle System when the direction is computed for the created particle.
  50496. * @param emitPower is the power of the particle (speed)
  50497. * @param worldMatrix is the world matrix of the particle system
  50498. * @param directionToUpdate is the direction vector to update with the result
  50499. * @param particle is the particle we are computed the direction for
  50500. */
  50501. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50502. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  50503. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  50504. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  50505. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  50506. };
  50507. /**
  50508. * Called by the particle System when the position is computed for the created particle.
  50509. * @param worldMatrix is the world matrix of the particle system
  50510. * @param positionToUpdate is the position vector to update with the result
  50511. * @param particle is the particle we are computed the position for
  50512. */
  50513. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  50514. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  50515. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  50516. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  50517. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  50518. };
  50519. /**
  50520. * Clones the current emitter and returns a copy of it
  50521. * @returns the new emitter
  50522. */
  50523. BoxParticleEmitter.prototype.clone = function () {
  50524. var newOne = new BoxParticleEmitter(this._particleSystem);
  50525. BABYLON.Tools.DeepCopy(this, newOne);
  50526. return newOne;
  50527. };
  50528. return BoxParticleEmitter;
  50529. }());
  50530. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  50531. })(BABYLON || (BABYLON = {}));
  50532. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  50533. var BABYLON;
  50534. (function (BABYLON) {
  50535. /**
  50536. * Particle emitter emitting particles from the inside of a cone.
  50537. * It emits the particles alongside the cone volume from the base to the particle.
  50538. * The emission direction might be randomized.
  50539. */
  50540. var ConeParticleEmitter = /** @class */ (function () {
  50541. /**
  50542. * Creates a new instance of @see ConeParticleEmitter
  50543. * @param radius the radius of the emission cone
  50544. * @param angles the cone base angle
  50545. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  50546. */
  50547. function ConeParticleEmitter(radius,
  50548. /**
  50549. * The radius of the emission cone.
  50550. */
  50551. angle,
  50552. /**
  50553. * The cone base angle.
  50554. */
  50555. directionRandomizer) {
  50556. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  50557. this.angle = angle;
  50558. this.directionRandomizer = directionRandomizer;
  50559. this.radius = radius;
  50560. }
  50561. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  50562. /**
  50563. * Gets the radius of the emission cone.
  50564. */
  50565. get: function () {
  50566. return this._radius;
  50567. },
  50568. /**
  50569. * Sets the radius of the emission cone.
  50570. */
  50571. set: function (value) {
  50572. this._radius = value;
  50573. if (this.angle !== 0) {
  50574. this._height = value / Math.tan(this.angle / 2);
  50575. }
  50576. else {
  50577. this._height = 1;
  50578. }
  50579. },
  50580. enumerable: true,
  50581. configurable: true
  50582. });
  50583. /**
  50584. * Called by the particle System when the direction is computed for the created particle.
  50585. * @param emitPower is the power of the particle (speed)
  50586. * @param worldMatrix is the world matrix of the particle system
  50587. * @param directionToUpdate is the direction vector to update with the result
  50588. * @param particle is the particle we are computed the direction for
  50589. */
  50590. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50591. if (this.angle === 0) {
  50592. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  50593. }
  50594. else {
  50595. // measure the direction Vector from the emitter to the particle.
  50596. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  50597. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50598. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50599. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50600. direction.x += randX;
  50601. direction.y += randY;
  50602. direction.z += randZ;
  50603. direction.normalize();
  50604. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  50605. }
  50606. };
  50607. /**
  50608. * Called by the particle System when the position is computed for the created particle.
  50609. * @param worldMatrix is the world matrix of the particle system
  50610. * @param positionToUpdate is the position vector to update with the result
  50611. * @param particle is the particle we are computed the position for
  50612. */
  50613. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  50614. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  50615. var h = BABYLON.Scalar.RandomRange(0, 1);
  50616. // Better distribution in a cone at normal angles.
  50617. h = 1 - h * h;
  50618. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  50619. radius = radius * h / this._height;
  50620. var randX = radius * Math.sin(s);
  50621. var randZ = radius * Math.cos(s);
  50622. var randY = h;
  50623. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  50624. };
  50625. /**
  50626. * Clones the current emitter and returns a copy of it
  50627. * @returns the new emitter
  50628. */
  50629. ConeParticleEmitter.prototype.clone = function () {
  50630. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  50631. BABYLON.Tools.DeepCopy(this, newOne);
  50632. return newOne;
  50633. };
  50634. return ConeParticleEmitter;
  50635. }());
  50636. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  50637. })(BABYLON || (BABYLON = {}));
  50638. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  50639. var BABYLON;
  50640. (function (BABYLON) {
  50641. /**
  50642. * Particle emitter emitting particles from the inside of a sphere.
  50643. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  50644. */
  50645. var SphereParticleEmitter = /** @class */ (function () {
  50646. /**
  50647. * Creates a new instance of @see SphereParticleEmitter
  50648. * @param radius the radius of the emission sphere
  50649. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  50650. */
  50651. function SphereParticleEmitter(
  50652. /**
  50653. * The radius of the emission sphere.
  50654. */
  50655. radius,
  50656. /**
  50657. * How much to randomize the particle direction [0-1].
  50658. */
  50659. directionRandomizer) {
  50660. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  50661. this.radius = radius;
  50662. this.directionRandomizer = directionRandomizer;
  50663. }
  50664. /**
  50665. * Called by the particle System when the direction is computed for the created particle.
  50666. * @param emitPower is the power of the particle (speed)
  50667. * @param worldMatrix is the world matrix of the particle system
  50668. * @param directionToUpdate is the direction vector to update with the result
  50669. * @param particle is the particle we are computed the direction for
  50670. */
  50671. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50672. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  50673. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50674. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50675. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50676. direction.x += randX;
  50677. direction.y += randY;
  50678. direction.z += randZ;
  50679. direction.normalize();
  50680. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  50681. };
  50682. /**
  50683. * Called by the particle System when the position is computed for the created particle.
  50684. * @param worldMatrix is the world matrix of the particle system
  50685. * @param positionToUpdate is the position vector to update with the result
  50686. * @param particle is the particle we are computed the position for
  50687. */
  50688. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  50689. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  50690. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  50691. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  50692. var randY = this.radius * Math.cos(theta);
  50693. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  50694. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  50695. };
  50696. /**
  50697. * Clones the current emitter and returns a copy of it
  50698. * @returns the new emitter
  50699. */
  50700. SphereParticleEmitter.prototype.clone = function () {
  50701. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  50702. BABYLON.Tools.DeepCopy(this, newOne);
  50703. return newOne;
  50704. };
  50705. return SphereParticleEmitter;
  50706. }());
  50707. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  50708. /**
  50709. * Particle emitter emitting particles from the inside of a sphere.
  50710. * It emits the particles randomly between two vectors.
  50711. */
  50712. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  50713. __extends(SphereDirectedParticleEmitter, _super);
  50714. /**
  50715. * Creates a new instance of @see SphereDirectedParticleEmitter
  50716. * @param radius the radius of the emission sphere
  50717. * @param direction1 the min limit of the emission direction
  50718. * @param direction2 the max limit of the emission direction
  50719. */
  50720. function SphereDirectedParticleEmitter(radius,
  50721. /**
  50722. * The min limit of the emission direction.
  50723. */
  50724. direction1,
  50725. /**
  50726. * The max limit of the emission direction.
  50727. */
  50728. direction2) {
  50729. var _this = _super.call(this, radius) || this;
  50730. _this.direction1 = direction1;
  50731. _this.direction2 = direction2;
  50732. return _this;
  50733. }
  50734. /**
  50735. * Called by the particle System when the direction is computed for the created particle.
  50736. * @param emitPower is the power of the particle (speed)
  50737. * @param worldMatrix is the world matrix of the particle system
  50738. * @param directionToUpdate is the direction vector to update with the result
  50739. * @param particle is the particle we are computed the direction for
  50740. */
  50741. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50742. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  50743. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  50744. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  50745. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  50746. };
  50747. /**
  50748. * Clones the current emitter and returns a copy of it
  50749. * @returns the new emitter
  50750. */
  50751. SphereDirectedParticleEmitter.prototype.clone = function () {
  50752. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  50753. BABYLON.Tools.DeepCopy(this, newOne);
  50754. return newOne;
  50755. };
  50756. return SphereDirectedParticleEmitter;
  50757. }(SphereParticleEmitter));
  50758. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  50759. })(BABYLON || (BABYLON = {}));
  50760. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  50761. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  50762. var BABYLON;
  50763. (function (BABYLON) {
  50764. /**
  50765. * Represents one particle of a solid particle system.
  50766. * @see SolidParticleSystem
  50767. */
  50768. var SolidParticle = /** @class */ (function () {
  50769. /**
  50770. * Creates a Solid Particle object.
  50771. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  50772. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  50773. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  50774. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  50775. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  50776. * @param shapeId (integer) is the model shape identifier in the SPS.
  50777. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  50778. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  50779. */
  50780. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  50781. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  50782. /**
  50783. * particle global index
  50784. */
  50785. this.idx = 0;
  50786. /**
  50787. * The color of the particle
  50788. */
  50789. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50790. /**
  50791. * The world space position of the particle.
  50792. */
  50793. this.position = BABYLON.Vector3.Zero();
  50794. /**
  50795. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  50796. */
  50797. this.rotation = BABYLON.Vector3.Zero();
  50798. /**
  50799. * The scaling of the particle.
  50800. */
  50801. this.scaling = BABYLON.Vector3.One();
  50802. /**
  50803. * The uvs of the particle.
  50804. */
  50805. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  50806. /**
  50807. * The current speed of the particle.
  50808. */
  50809. this.velocity = BABYLON.Vector3.Zero();
  50810. /**
  50811. * The pivot point in the particle local space.
  50812. */
  50813. this.pivot = BABYLON.Vector3.Zero();
  50814. /**
  50815. * Must the particle be translated from its pivot point in its local space ?
  50816. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  50817. * Default : false
  50818. */
  50819. this.translateFromPivot = false;
  50820. /**
  50821. * Is the particle active or not ?
  50822. */
  50823. this.alive = true;
  50824. /**
  50825. * Is the particle visible or not ?
  50826. */
  50827. this.isVisible = true;
  50828. /**
  50829. * Index of this particle in the global "positions" array (Internal use)
  50830. */
  50831. this._pos = 0;
  50832. /**
  50833. * Index of this particle in the global "indices" array (Internal use)
  50834. */
  50835. this._ind = 0;
  50836. /**
  50837. * ModelShape id of this particle
  50838. */
  50839. this.shapeId = 0;
  50840. /**
  50841. * Index of the particle in its shape id (Internal use)
  50842. */
  50843. this.idxInShape = 0;
  50844. /**
  50845. * Still set as invisible in order to skip useless computations (Internal use)
  50846. */
  50847. this._stillInvisible = false;
  50848. /**
  50849. * Last computed particle rotation matrix
  50850. */
  50851. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  50852. this.idx = particleIndex;
  50853. this._pos = positionIndex;
  50854. this._ind = indiceIndex;
  50855. this._model = model;
  50856. this.shapeId = shapeId;
  50857. this.idxInShape = idxInShape;
  50858. this._sps = sps;
  50859. if (modelBoundingInfo) {
  50860. this._modelBoundingInfo = modelBoundingInfo;
  50861. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  50862. }
  50863. }
  50864. Object.defineProperty(SolidParticle.prototype, "scale", {
  50865. /**
  50866. * Legacy support, changed scale to scaling
  50867. */
  50868. get: function () {
  50869. return this.scaling;
  50870. },
  50871. /**
  50872. * Legacy support, changed scale to scaling
  50873. */
  50874. set: function (scale) {
  50875. this.scaling = scale;
  50876. },
  50877. enumerable: true,
  50878. configurable: true
  50879. });
  50880. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  50881. /**
  50882. * Legacy support, changed quaternion to rotationQuaternion
  50883. */
  50884. get: function () {
  50885. return this.rotationQuaternion;
  50886. },
  50887. /**
  50888. * Legacy support, changed quaternion to rotationQuaternion
  50889. */
  50890. set: function (q) {
  50891. this.rotationQuaternion = q;
  50892. },
  50893. enumerable: true,
  50894. configurable: true
  50895. });
  50896. /**
  50897. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  50898. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  50899. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  50900. * @returns true if it intersects
  50901. */
  50902. SolidParticle.prototype.intersectsMesh = function (target) {
  50903. if (!this._boundingInfo || !target._boundingInfo) {
  50904. return false;
  50905. }
  50906. if (this._sps._bSphereOnly) {
  50907. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  50908. }
  50909. return this._boundingInfo.intersects(target._boundingInfo, false);
  50910. };
  50911. return SolidParticle;
  50912. }());
  50913. BABYLON.SolidParticle = SolidParticle;
  50914. /**
  50915. * Represents the shape of the model used by one particle of a solid particle system.
  50916. * SPS internal tool, don't use it manually.
  50917. * @see SolidParticleSystem
  50918. */
  50919. var ModelShape = /** @class */ (function () {
  50920. /**
  50921. * 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.
  50922. * SPS internal tool, don't use it manually.
  50923. * @ignore
  50924. */
  50925. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  50926. /**
  50927. * length of the shape in the model indices array (internal use)
  50928. */
  50929. this._indicesLength = 0;
  50930. this.shapeID = id;
  50931. this._shape = shape;
  50932. this._indicesLength = indicesLength;
  50933. this._shapeUV = shapeUV;
  50934. this._positionFunction = posFunction;
  50935. this._vertexFunction = vtxFunction;
  50936. }
  50937. return ModelShape;
  50938. }());
  50939. BABYLON.ModelShape = ModelShape;
  50940. /**
  50941. * Represents a Depth Sorted Particle in the solid particle system.
  50942. * @see SolidParticleSystem
  50943. */
  50944. var DepthSortedParticle = /** @class */ (function () {
  50945. function DepthSortedParticle() {
  50946. /**
  50947. * Index of the particle in the "indices" array
  50948. */
  50949. this.ind = 0;
  50950. /**
  50951. * Length of the particle shape in the "indices" array
  50952. */
  50953. this.indicesLength = 0;
  50954. /**
  50955. * Squared distance from the particle to the camera
  50956. */
  50957. this.sqDistance = 0.0;
  50958. }
  50959. return DepthSortedParticle;
  50960. }());
  50961. BABYLON.DepthSortedParticle = DepthSortedParticle;
  50962. })(BABYLON || (BABYLON = {}));
  50963. //# sourceMappingURL=babylon.solidParticle.js.map
  50964. var BABYLON;
  50965. (function (BABYLON) {
  50966. /**
  50967. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  50968. *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.
  50969. * The SPS is also a particle system. It provides some methods to manage the particles.
  50970. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  50971. *
  50972. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  50973. */
  50974. var SolidParticleSystem = /** @class */ (function () {
  50975. /**
  50976. * Creates a SPS (Solid Particle System) object.
  50977. * @param name (String) is the SPS name, this will be the underlying mesh name.
  50978. * @param scene (Scene) is the scene in which the SPS is added.
  50979. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  50980. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  50981. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  50982. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  50983. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  50984. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  50985. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  50986. */
  50987. function SolidParticleSystem(name, scene, options) {
  50988. /**
  50989. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  50990. * Example : var p = SPS.particles[i];
  50991. */
  50992. this.particles = new Array();
  50993. /**
  50994. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  50995. */
  50996. this.nbParticles = 0;
  50997. /**
  50998. * If the particles must ever face the camera (default false). Useful for planar particles.
  50999. */
  51000. this.billboard = false;
  51001. /**
  51002. * Recompute normals when adding a shape
  51003. */
  51004. this.recomputeNormals = true;
  51005. /**
  51006. * This a counter ofr your own usage. It's not set by any SPS functions.
  51007. */
  51008. this.counter = 0;
  51009. /**
  51010. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  51011. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  51012. */
  51013. this.vars = {};
  51014. /**
  51015. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  51016. */
  51017. this._bSphereOnly = false;
  51018. /**
  51019. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  51020. */
  51021. this._bSphereRadiusFactor = 1.0;
  51022. this._positions = new Array();
  51023. this._indices = new Array();
  51024. this._normals = new Array();
  51025. this._colors = new Array();
  51026. this._uvs = new Array();
  51027. this._index = 0; // indices index
  51028. this._updatable = true;
  51029. this._pickable = false;
  51030. this._isVisibilityBoxLocked = false;
  51031. this._alwaysVisible = false;
  51032. this._depthSort = false;
  51033. this._shapeCounter = 0;
  51034. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  51035. this._color = new BABYLON.Color4(0, 0, 0, 0);
  51036. this._computeParticleColor = true;
  51037. this._computeParticleTexture = true;
  51038. this._computeParticleRotation = true;
  51039. this._computeParticleVertex = false;
  51040. this._computeBoundingBox = false;
  51041. this._depthSortParticles = true;
  51042. this._cam_axisZ = BABYLON.Vector3.Zero();
  51043. this._cam_axisY = BABYLON.Vector3.Zero();
  51044. this._cam_axisX = BABYLON.Vector3.Zero();
  51045. this._axisZ = BABYLON.Axis.Z;
  51046. this._camDir = BABYLON.Vector3.Zero();
  51047. this._camInvertedPosition = BABYLON.Vector3.Zero();
  51048. this._rotMatrix = new BABYLON.Matrix();
  51049. this._invertMatrix = new BABYLON.Matrix();
  51050. this._rotated = BABYLON.Vector3.Zero();
  51051. this._quaternion = new BABYLON.Quaternion();
  51052. this._vertex = BABYLON.Vector3.Zero();
  51053. this._normal = BABYLON.Vector3.Zero();
  51054. this._yaw = 0.0;
  51055. this._pitch = 0.0;
  51056. this._roll = 0.0;
  51057. this._halfroll = 0.0;
  51058. this._halfpitch = 0.0;
  51059. this._halfyaw = 0.0;
  51060. this._sinRoll = 0.0;
  51061. this._cosRoll = 0.0;
  51062. this._sinPitch = 0.0;
  51063. this._cosPitch = 0.0;
  51064. this._sinYaw = 0.0;
  51065. this._cosYaw = 0.0;
  51066. this._mustUnrotateFixedNormals = false;
  51067. this._minimum = BABYLON.Tmp.Vector3[0];
  51068. this._maximum = BABYLON.Tmp.Vector3[1];
  51069. this._minBbox = BABYLON.Tmp.Vector3[4];
  51070. this._maxBbox = BABYLON.Tmp.Vector3[5];
  51071. this._particlesIntersect = false;
  51072. this._depthSortFunction = function (p1, p2) {
  51073. return (p2.sqDistance - p1.sqDistance);
  51074. };
  51075. this._needs32Bits = false;
  51076. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  51077. this.name = name;
  51078. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51079. this._camera = scene.activeCamera;
  51080. this._pickable = options ? options.isPickable : false;
  51081. this._depthSort = options ? options.enableDepthSort : false;
  51082. this._particlesIntersect = options ? options.particleIntersection : false;
  51083. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  51084. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  51085. if (options && options.updatable) {
  51086. this._updatable = options.updatable;
  51087. }
  51088. else {
  51089. this._updatable = true;
  51090. }
  51091. if (this._pickable) {
  51092. this.pickedParticles = [];
  51093. }
  51094. if (this._depthSort) {
  51095. this.depthSortedParticles = [];
  51096. }
  51097. }
  51098. /**
  51099. * Builds the SPS underlying mesh. Returns a standard Mesh.
  51100. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  51101. * @returns the created mesh
  51102. */
  51103. SolidParticleSystem.prototype.buildMesh = function () {
  51104. if (this.nbParticles === 0) {
  51105. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  51106. this.addShape(triangle, 1);
  51107. triangle.dispose();
  51108. }
  51109. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  51110. this._positions32 = new Float32Array(this._positions);
  51111. this._uvs32 = new Float32Array(this._uvs);
  51112. this._colors32 = new Float32Array(this._colors);
  51113. if (this.recomputeNormals) {
  51114. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  51115. }
  51116. this._normals32 = new Float32Array(this._normals);
  51117. this._fixedNormal32 = new Float32Array(this._normals);
  51118. if (this._mustUnrotateFixedNormals) {
  51119. this._unrotateFixedNormals();
  51120. }
  51121. var vertexData = new BABYLON.VertexData();
  51122. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  51123. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  51124. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  51125. if (this._uvs32) {
  51126. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  51127. ;
  51128. }
  51129. if (this._colors32) {
  51130. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  51131. }
  51132. var mesh = new BABYLON.Mesh(this.name, this._scene);
  51133. vertexData.applyToMesh(mesh, this._updatable);
  51134. this.mesh = mesh;
  51135. this.mesh.isPickable = this._pickable;
  51136. // free memory
  51137. if (!this._depthSort) {
  51138. this._indices = null;
  51139. }
  51140. this._positions = null;
  51141. this._normals = null;
  51142. this._uvs = null;
  51143. this._colors = null;
  51144. if (!this._updatable) {
  51145. this.particles.length = 0;
  51146. }
  51147. return mesh;
  51148. };
  51149. /**
  51150. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  51151. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  51152. * Thus the particles generated from `digest()` have their property `position` set yet.
  51153. * @param mesh ( Mesh ) is the mesh to be digested
  51154. * @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
  51155. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  51156. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  51157. * @returns the current SPS
  51158. */
  51159. SolidParticleSystem.prototype.digest = function (mesh, options) {
  51160. var size = (options && options.facetNb) || 1;
  51161. var number = (options && options.number) || 0;
  51162. var delta = (options && options.delta) || 0;
  51163. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51164. var meshInd = mesh.getIndices();
  51165. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51166. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51167. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51168. var f = 0; // facet counter
  51169. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  51170. // compute size from number
  51171. if (number) {
  51172. number = (number > totalFacets) ? totalFacets : number;
  51173. size = Math.round(totalFacets / number);
  51174. delta = 0;
  51175. }
  51176. else {
  51177. size = (size > totalFacets) ? totalFacets : size;
  51178. }
  51179. var facetPos = []; // submesh positions
  51180. var facetInd = []; // submesh indices
  51181. var facetUV = []; // submesh UV
  51182. var facetCol = []; // submesh colors
  51183. var barycenter = BABYLON.Tmp.Vector3[0];
  51184. var sizeO = size;
  51185. while (f < totalFacets) {
  51186. size = sizeO + Math.floor((1 + delta) * Math.random());
  51187. if (f > totalFacets - size) {
  51188. size = totalFacets - f;
  51189. }
  51190. // reset temp arrays
  51191. facetPos.length = 0;
  51192. facetInd.length = 0;
  51193. facetUV.length = 0;
  51194. facetCol.length = 0;
  51195. // iterate over "size" facets
  51196. var fi = 0;
  51197. for (var j = f * 3; j < (f + size) * 3; j++) {
  51198. facetInd.push(fi);
  51199. var i = meshInd[j];
  51200. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  51201. if (meshUV) {
  51202. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  51203. }
  51204. if (meshCol) {
  51205. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  51206. }
  51207. fi++;
  51208. }
  51209. // create a model shape for each single particle
  51210. var idx = this.nbParticles;
  51211. var shape = this._posToShape(facetPos);
  51212. var shapeUV = this._uvsToShapeUV(facetUV);
  51213. // compute the barycenter of the shape
  51214. var v;
  51215. for (v = 0; v < shape.length; v++) {
  51216. barycenter.addInPlace(shape[v]);
  51217. }
  51218. barycenter.scaleInPlace(1 / shape.length);
  51219. // shift the shape from its barycenter to the origin
  51220. for (v = 0; v < shape.length; v++) {
  51221. shape[v].subtractInPlace(barycenter);
  51222. }
  51223. var bInfo;
  51224. if (this._particlesIntersect) {
  51225. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  51226. }
  51227. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  51228. // add the particle in the SPS
  51229. var currentPos = this._positions.length;
  51230. var currentInd = this._indices.length;
  51231. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  51232. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  51233. // initialize the particle position
  51234. this.particles[this.nbParticles].position.addInPlace(barycenter);
  51235. this._index += shape.length;
  51236. idx++;
  51237. this.nbParticles++;
  51238. this._shapeCounter++;
  51239. f += size;
  51240. }
  51241. return this;
  51242. };
  51243. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  51244. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  51245. var index = 0;
  51246. var idx = 0;
  51247. for (var p = 0; p < this.particles.length; p++) {
  51248. this._particle = this.particles[p];
  51249. this._shape = this._particle._model._shape;
  51250. if (this._particle.rotationQuaternion) {
  51251. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  51252. }
  51253. else {
  51254. this._yaw = this._particle.rotation.y;
  51255. this._pitch = this._particle.rotation.x;
  51256. this._roll = this._particle.rotation.z;
  51257. this._quaternionRotationYPR();
  51258. }
  51259. this._quaternionToRotationMatrix();
  51260. this._rotMatrix.invertToRef(this._invertMatrix);
  51261. for (var pt = 0; pt < this._shape.length; pt++) {
  51262. idx = index + pt * 3;
  51263. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  51264. this._fixedNormal32[idx] = this._normal.x;
  51265. this._fixedNormal32[idx + 1] = this._normal.y;
  51266. this._fixedNormal32[idx + 2] = this._normal.z;
  51267. }
  51268. index = idx + 3;
  51269. }
  51270. };
  51271. //reset copy
  51272. SolidParticleSystem.prototype._resetCopy = function () {
  51273. this._copy.position.x = 0;
  51274. this._copy.position.y = 0;
  51275. this._copy.position.z = 0;
  51276. this._copy.rotation.x = 0;
  51277. this._copy.rotation.y = 0;
  51278. this._copy.rotation.z = 0;
  51279. this._copy.rotationQuaternion = null;
  51280. this._copy.scaling.x = 1.0;
  51281. this._copy.scaling.y = 1.0;
  51282. this._copy.scaling.z = 1.0;
  51283. this._copy.uvs.x = 0;
  51284. this._copy.uvs.y = 0;
  51285. this._copy.uvs.z = 1.0;
  51286. this._copy.uvs.w = 1.0;
  51287. this._copy.color = null;
  51288. this._copy.translateFromPivot = false;
  51289. };
  51290. // _meshBuilder : inserts the shape model in the global SPS mesh
  51291. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  51292. var i;
  51293. var u = 0;
  51294. var c = 0;
  51295. var n = 0;
  51296. this._resetCopy();
  51297. if (options && options.positionFunction) {
  51298. options.positionFunction(this._copy, idx, idxInShape);
  51299. this._mustUnrotateFixedNormals = true;
  51300. }
  51301. if (this._copy.rotationQuaternion) {
  51302. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  51303. }
  51304. else {
  51305. this._yaw = this._copy.rotation.y;
  51306. this._pitch = this._copy.rotation.x;
  51307. this._roll = this._copy.rotation.z;
  51308. this._quaternionRotationYPR();
  51309. }
  51310. this._quaternionToRotationMatrix();
  51311. if (this._copy.translateFromPivot) {
  51312. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  51313. }
  51314. else {
  51315. this._pivotBackTranslation.copyFrom(this._copy.pivot);
  51316. }
  51317. for (i = 0; i < shape.length; i++) {
  51318. this._vertex.x = shape[i].x;
  51319. this._vertex.y = shape[i].y;
  51320. this._vertex.z = shape[i].z;
  51321. if (options && options.vertexFunction) {
  51322. options.vertexFunction(this._copy, this._vertex, i);
  51323. }
  51324. this._vertex.x *= this._copy.scaling.x;
  51325. this._vertex.y *= this._copy.scaling.y;
  51326. this._vertex.z *= this._copy.scaling.z;
  51327. this._vertex.x -= this._copy.pivot.x;
  51328. this._vertex.y -= this._copy.pivot.y;
  51329. this._vertex.z -= this._copy.pivot.z;
  51330. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  51331. this._rotated.addInPlace(this._pivotBackTranslation);
  51332. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  51333. if (meshUV) {
  51334. 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);
  51335. u += 2;
  51336. }
  51337. if (this._copy.color) {
  51338. this._color = this._copy.color;
  51339. }
  51340. else if (meshCol && meshCol[c] !== undefined) {
  51341. this._color.r = meshCol[c];
  51342. this._color.g = meshCol[c + 1];
  51343. this._color.b = meshCol[c + 2];
  51344. this._color.a = meshCol[c + 3];
  51345. }
  51346. else {
  51347. this._color.r = 1.0;
  51348. this._color.g = 1.0;
  51349. this._color.b = 1.0;
  51350. this._color.a = 1.0;
  51351. }
  51352. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  51353. c += 4;
  51354. if (!this.recomputeNormals && meshNor) {
  51355. this._normal.x = meshNor[n];
  51356. this._normal.y = meshNor[n + 1];
  51357. this._normal.z = meshNor[n + 2];
  51358. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  51359. normals.push(this._normal.x, this._normal.y, this._normal.z);
  51360. n += 3;
  51361. }
  51362. }
  51363. for (i = 0; i < meshInd.length; i++) {
  51364. var current_ind = p + meshInd[i];
  51365. indices.push(current_ind);
  51366. if (current_ind > 65535) {
  51367. this._needs32Bits = true;
  51368. }
  51369. }
  51370. if (this._pickable) {
  51371. var nbfaces = meshInd.length / 3;
  51372. for (i = 0; i < nbfaces; i++) {
  51373. this.pickedParticles.push({ idx: idx, faceId: i });
  51374. }
  51375. }
  51376. if (this._depthSort) {
  51377. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  51378. }
  51379. return this._copy;
  51380. };
  51381. // returns a shape array from positions array
  51382. SolidParticleSystem.prototype._posToShape = function (positions) {
  51383. var shape = [];
  51384. for (var i = 0; i < positions.length; i += 3) {
  51385. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  51386. }
  51387. return shape;
  51388. };
  51389. // returns a shapeUV array from a Vector4 uvs
  51390. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  51391. var shapeUV = [];
  51392. if (uvs) {
  51393. for (var i = 0; i < uvs.length; i++)
  51394. shapeUV.push(uvs[i]);
  51395. }
  51396. return shapeUV;
  51397. };
  51398. // adds a new particle object in the particles array
  51399. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  51400. if (bInfo === void 0) { bInfo = null; }
  51401. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  51402. this.particles.push(sp);
  51403. return sp;
  51404. };
  51405. /**
  51406. * Adds some particles to the SPS from the model shape. Returns the shape id.
  51407. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  51408. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  51409. * @param nb (positive integer) the number of particles to be created from this model
  51410. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  51411. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  51412. * @returns the number of shapes in the system
  51413. */
  51414. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  51415. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51416. var meshInd = mesh.getIndices();
  51417. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51418. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51419. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51420. var bbInfo;
  51421. if (this._particlesIntersect) {
  51422. bbInfo = mesh.getBoundingInfo();
  51423. }
  51424. var shape = this._posToShape(meshPos);
  51425. var shapeUV = this._uvsToShapeUV(meshUV);
  51426. var posfunc = options ? options.positionFunction : null;
  51427. var vtxfunc = options ? options.vertexFunction : null;
  51428. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  51429. // particles
  51430. var sp;
  51431. var currentCopy;
  51432. var idx = this.nbParticles;
  51433. for (var i = 0; i < nb; i++) {
  51434. var currentPos = this._positions.length;
  51435. var currentInd = this._indices.length;
  51436. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  51437. if (this._updatable) {
  51438. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  51439. sp.position.copyFrom(currentCopy.position);
  51440. sp.rotation.copyFrom(currentCopy.rotation);
  51441. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  51442. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  51443. }
  51444. if (currentCopy.color && sp.color) {
  51445. sp.color.copyFrom(currentCopy.color);
  51446. }
  51447. sp.scaling.copyFrom(currentCopy.scaling);
  51448. sp.uvs.copyFrom(currentCopy.uvs);
  51449. }
  51450. this._index += shape.length;
  51451. idx++;
  51452. }
  51453. this.nbParticles += nb;
  51454. this._shapeCounter++;
  51455. return this._shapeCounter - 1;
  51456. };
  51457. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  51458. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  51459. this._resetCopy();
  51460. if (particle._model._positionFunction) {
  51461. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  51462. }
  51463. if (this._copy.rotationQuaternion) {
  51464. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  51465. }
  51466. else {
  51467. this._yaw = this._copy.rotation.y;
  51468. this._pitch = this._copy.rotation.x;
  51469. this._roll = this._copy.rotation.z;
  51470. this._quaternionRotationYPR();
  51471. }
  51472. this._quaternionToRotationMatrix();
  51473. if (this._copy.translateFromPivot) {
  51474. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  51475. }
  51476. else {
  51477. this._pivotBackTranslation.copyFrom(this._copy.pivot);
  51478. }
  51479. this._shape = particle._model._shape;
  51480. for (var pt = 0; pt < this._shape.length; pt++) {
  51481. this._vertex.x = this._shape[pt].x;
  51482. this._vertex.y = this._shape[pt].y;
  51483. this._vertex.z = this._shape[pt].z;
  51484. if (particle._model._vertexFunction) {
  51485. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  51486. }
  51487. this._vertex.x *= this._copy.scaling.x;
  51488. this._vertex.y *= this._copy.scaling.y;
  51489. this._vertex.z *= this._copy.scaling.z;
  51490. this._vertex.x -= this._copy.pivot.x;
  51491. this._vertex.y -= this._copy.pivot.y;
  51492. this._vertex.z -= this._copy.pivot.z;
  51493. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  51494. this._rotated.addInPlace(this._pivotBackTranslation);
  51495. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  51496. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  51497. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  51498. }
  51499. particle.position.x = 0.0;
  51500. particle.position.y = 0.0;
  51501. particle.position.z = 0.0;
  51502. particle.rotation.x = 0.0;
  51503. particle.rotation.y = 0.0;
  51504. particle.rotation.z = 0.0;
  51505. particle.rotationQuaternion = null;
  51506. particle.scaling.x = 1.0;
  51507. particle.scaling.y = 1.0;
  51508. particle.scaling.z = 1.0;
  51509. };
  51510. /**
  51511. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  51512. * @returns the SPS.
  51513. */
  51514. SolidParticleSystem.prototype.rebuildMesh = function () {
  51515. for (var p = 0; p < this.particles.length; p++) {
  51516. this._rebuildParticle(this.particles[p]);
  51517. }
  51518. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  51519. return this;
  51520. };
  51521. /**
  51522. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  51523. * This method calls `updateParticle()` for each particle of the SPS.
  51524. * For an animated SPS, it is usually called within the render loop.
  51525. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  51526. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  51527. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  51528. * @returns the SPS.
  51529. */
  51530. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  51531. if (start === void 0) { start = 0; }
  51532. if (end === void 0) { end = this.nbParticles - 1; }
  51533. if (update === void 0) { update = true; }
  51534. if (!this._updatable) {
  51535. return this;
  51536. }
  51537. // custom beforeUpdate
  51538. this.beforeUpdateParticles(start, end, update);
  51539. this._cam_axisX.x = 1.0;
  51540. this._cam_axisX.y = 0.0;
  51541. this._cam_axisX.z = 0.0;
  51542. this._cam_axisY.x = 0.0;
  51543. this._cam_axisY.y = 1.0;
  51544. this._cam_axisY.z = 0.0;
  51545. this._cam_axisZ.x = 0.0;
  51546. this._cam_axisZ.y = 0.0;
  51547. this._cam_axisZ.z = 1.0;
  51548. // cases when the World Matrix is to be computed first
  51549. if (this.billboard || this._depthSort) {
  51550. this.mesh.computeWorldMatrix(true);
  51551. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  51552. }
  51553. // if the particles will always face the camera
  51554. if (this.billboard) {
  51555. // compute the camera position and un-rotate it by the current mesh rotation
  51556. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  51557. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  51558. this._cam_axisZ.normalize();
  51559. // same for camera up vector extracted from the cam view matrix
  51560. var view = this._camera.getViewMatrix(true);
  51561. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  51562. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  51563. this._cam_axisY.normalize();
  51564. this._cam_axisX.normalize();
  51565. }
  51566. // if depthSort, compute the camera global position in the mesh local system
  51567. if (this._depthSort) {
  51568. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  51569. }
  51570. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  51571. var idx = 0; // current position index in the global array positions32
  51572. var index = 0; // position start index in the global array positions32 of the current particle
  51573. var colidx = 0; // current color index in the global array colors32
  51574. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  51575. var uvidx = 0; // current uv index in the global array uvs32
  51576. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  51577. var pt = 0; // current index in the particle model shape
  51578. if (this.mesh.isFacetDataEnabled) {
  51579. this._computeBoundingBox = true;
  51580. }
  51581. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  51582. if (this._computeBoundingBox) {
  51583. if (start == 0 && end == this.nbParticles - 1) {
  51584. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  51585. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  51586. }
  51587. else {
  51588. if (this.mesh._boundingInfo) {
  51589. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  51590. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  51591. }
  51592. }
  51593. }
  51594. // particle loop
  51595. index = this.particles[start]._pos;
  51596. var vpos = (index / 3) | 0;
  51597. colorIndex = vpos * 4;
  51598. uvIndex = vpos * 2;
  51599. for (var p = start; p <= end; p++) {
  51600. this._particle = this.particles[p];
  51601. this._shape = this._particle._model._shape;
  51602. this._shapeUV = this._particle._model._shapeUV;
  51603. // call to custom user function to update the particle properties
  51604. this.updateParticle(this._particle);
  51605. // camera-particle distance for depth sorting
  51606. if (this._depthSort && this._depthSortParticles) {
  51607. var dsp = this.depthSortedParticles[p];
  51608. dsp.ind = this._particle._ind;
  51609. dsp.indicesLength = this._particle._model._indicesLength;
  51610. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  51611. }
  51612. // skip the computations for inactive or already invisible particles
  51613. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  51614. // increment indexes for the next particle
  51615. pt = this._shape.length;
  51616. index += pt * 3;
  51617. colorIndex += pt * 4;
  51618. uvIndex += pt * 2;
  51619. continue;
  51620. }
  51621. if (this._particle.isVisible) {
  51622. this._particle._stillInvisible = false; // un-mark permanent invisibility
  51623. // particle rotation matrix
  51624. if (this.billboard) {
  51625. this._particle.rotation.x = 0.0;
  51626. this._particle.rotation.y = 0.0;
  51627. }
  51628. if (this._computeParticleRotation || this.billboard) {
  51629. if (this._particle.rotationQuaternion) {
  51630. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  51631. }
  51632. else {
  51633. this._yaw = this._particle.rotation.y;
  51634. this._pitch = this._particle.rotation.x;
  51635. this._roll = this._particle.rotation.z;
  51636. this._quaternionRotationYPR();
  51637. }
  51638. this._quaternionToRotationMatrix();
  51639. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  51640. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  51641. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  51642. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  51643. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  51644. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  51645. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  51646. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  51647. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  51648. }
  51649. if (this._particle.translateFromPivot) {
  51650. this._pivotBackTranslation.x = 0.0;
  51651. this._pivotBackTranslation.y = 0.0;
  51652. this._pivotBackTranslation.z = 0.0;
  51653. }
  51654. else {
  51655. this._pivotBackTranslation.x = this._particle.pivot.x;
  51656. this._pivotBackTranslation.y = this._particle.pivot.y;
  51657. this._pivotBackTranslation.z = this._particle.pivot.z;
  51658. }
  51659. // particle vertex loop
  51660. for (pt = 0; pt < this._shape.length; pt++) {
  51661. idx = index + pt * 3;
  51662. colidx = colorIndex + pt * 4;
  51663. uvidx = uvIndex + pt * 2;
  51664. this._vertex.x = this._shape[pt].x;
  51665. this._vertex.y = this._shape[pt].y;
  51666. this._vertex.z = this._shape[pt].z;
  51667. if (this._computeParticleVertex) {
  51668. this.updateParticleVertex(this._particle, this._vertex, pt);
  51669. }
  51670. // positions
  51671. this._vertex.x *= this._particle.scaling.x;
  51672. this._vertex.y *= this._particle.scaling.y;
  51673. this._vertex.z *= this._particle.scaling.z;
  51674. this._vertex.x -= this._particle.pivot.x;
  51675. this._vertex.y -= this._particle.pivot.y;
  51676. this._vertex.z -= this._particle.pivot.z;
  51677. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  51678. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  51679. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  51680. this._rotated.x += this._pivotBackTranslation.x;
  51681. this._rotated.y += this._pivotBackTranslation.y;
  51682. this._rotated.z += this._pivotBackTranslation.z;
  51683. this._positions32[idx] = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  51684. this._positions32[idx + 1] = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  51685. this._positions32[idx + 2] = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  51686. if (this._computeBoundingBox) {
  51687. if (this._positions32[idx] < this._minimum.x) {
  51688. this._minimum.x = this._positions32[idx];
  51689. }
  51690. if (this._positions32[idx] > this._maximum.x) {
  51691. this._maximum.x = this._positions32[idx];
  51692. }
  51693. if (this._positions32[idx + 1] < this._minimum.y) {
  51694. this._minimum.y = this._positions32[idx + 1];
  51695. }
  51696. if (this._positions32[idx + 1] > this._maximum.y) {
  51697. this._maximum.y = this._positions32[idx + 1];
  51698. }
  51699. if (this._positions32[idx + 2] < this._minimum.z) {
  51700. this._minimum.z = this._positions32[idx + 2];
  51701. }
  51702. if (this._positions32[idx + 2] > this._maximum.z) {
  51703. this._maximum.z = this._positions32[idx + 2];
  51704. }
  51705. }
  51706. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  51707. if (!this._computeParticleVertex) {
  51708. this._normal.x = this._fixedNormal32[idx];
  51709. this._normal.y = this._fixedNormal32[idx + 1];
  51710. this._normal.z = this._fixedNormal32[idx + 2];
  51711. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  51712. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  51713. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  51714. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  51715. 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;
  51716. 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;
  51717. }
  51718. if (this._computeParticleColor && this._particle.color) {
  51719. this._colors32[colidx] = this._particle.color.r;
  51720. this._colors32[colidx + 1] = this._particle.color.g;
  51721. this._colors32[colidx + 2] = this._particle.color.b;
  51722. this._colors32[colidx + 3] = this._particle.color.a;
  51723. }
  51724. if (this._computeParticleTexture) {
  51725. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  51726. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  51727. }
  51728. }
  51729. }
  51730. else {
  51731. this._particle._stillInvisible = true; // mark the particle as invisible
  51732. for (pt = 0; pt < this._shape.length; pt++) {
  51733. idx = index + pt * 3;
  51734. colidx = colorIndex + pt * 4;
  51735. uvidx = uvIndex + pt * 2;
  51736. this._positions32[idx] = 0.0;
  51737. this._positions32[idx + 1] = 0.0;
  51738. this._positions32[idx + 2] = 0.0;
  51739. this._normals32[idx] = 0.0;
  51740. this._normals32[idx + 1] = 0.0;
  51741. this._normals32[idx + 2] = 0.0;
  51742. if (this._computeParticleColor && this._particle.color) {
  51743. this._colors32[colidx] = this._particle.color.r;
  51744. this._colors32[colidx + 1] = this._particle.color.g;
  51745. this._colors32[colidx + 2] = this._particle.color.b;
  51746. this._colors32[colidx + 3] = this._particle.color.a;
  51747. }
  51748. if (this._computeParticleTexture) {
  51749. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  51750. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  51751. }
  51752. }
  51753. }
  51754. // if the particle intersections must be computed : update the bbInfo
  51755. if (this._particlesIntersect) {
  51756. var bInfo = this._particle._boundingInfo;
  51757. var bBox = bInfo.boundingBox;
  51758. var bSphere = bInfo.boundingSphere;
  51759. if (!this._bSphereOnly) {
  51760. // place, scale and rotate the particle bbox within the SPS local system, then update it
  51761. for (var b = 0; b < bBox.vectors.length; b++) {
  51762. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  51763. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  51764. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  51765. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  51766. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  51767. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  51768. 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;
  51769. 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;
  51770. 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;
  51771. }
  51772. bBox._update(this.mesh._worldMatrix);
  51773. }
  51774. // place and scale the particle bouding sphere in the SPS local system, then update it
  51775. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  51776. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  51777. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  51778. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  51779. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  51780. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  51781. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  51782. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  51783. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  51784. 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));
  51785. bSphere._update(this.mesh._worldMatrix);
  51786. }
  51787. // increment indexes for the next particle
  51788. index = idx + 3;
  51789. colorIndex = colidx + 4;
  51790. uvIndex = uvidx + 2;
  51791. }
  51792. // if the VBO must be updated
  51793. if (update) {
  51794. if (this._computeParticleColor) {
  51795. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  51796. }
  51797. if (this._computeParticleTexture) {
  51798. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  51799. }
  51800. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  51801. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  51802. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  51803. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  51804. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  51805. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  51806. for (var i = 0; i < this._normals32.length; i++) {
  51807. this._fixedNormal32[i] = this._normals32[i];
  51808. }
  51809. }
  51810. if (!this.mesh.areNormalsFrozen) {
  51811. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  51812. }
  51813. }
  51814. if (this._depthSort && this._depthSortParticles) {
  51815. this.depthSortedParticles.sort(this._depthSortFunction);
  51816. var dspl = this.depthSortedParticles.length;
  51817. var sorted = 0;
  51818. var lind = 0;
  51819. var sind = 0;
  51820. var sid = 0;
  51821. for (sorted = 0; sorted < dspl; sorted++) {
  51822. lind = this.depthSortedParticles[sorted].indicesLength;
  51823. sind = this.depthSortedParticles[sorted].ind;
  51824. for (var i = 0; i < lind; i++) {
  51825. this._indices32[sid] = this._indices[sind + i];
  51826. sid++;
  51827. }
  51828. }
  51829. this.mesh.updateIndices(this._indices32);
  51830. }
  51831. }
  51832. if (this._computeBoundingBox) {
  51833. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  51834. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  51835. }
  51836. this.afterUpdateParticles(start, end, update);
  51837. return this;
  51838. };
  51839. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  51840. this._halfroll = this._roll * 0.5;
  51841. this._halfpitch = this._pitch * 0.5;
  51842. this._halfyaw = this._yaw * 0.5;
  51843. this._sinRoll = Math.sin(this._halfroll);
  51844. this._cosRoll = Math.cos(this._halfroll);
  51845. this._sinPitch = Math.sin(this._halfpitch);
  51846. this._cosPitch = Math.cos(this._halfpitch);
  51847. this._sinYaw = Math.sin(this._halfyaw);
  51848. this._cosYaw = Math.cos(this._halfyaw);
  51849. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  51850. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  51851. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  51852. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  51853. };
  51854. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  51855. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  51856. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  51857. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  51858. this._rotMatrix.m[3] = 0;
  51859. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  51860. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  51861. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  51862. this._rotMatrix.m[7] = 0;
  51863. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  51864. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  51865. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  51866. this._rotMatrix.m[11] = 0;
  51867. this._rotMatrix.m[12] = 0;
  51868. this._rotMatrix.m[13] = 0;
  51869. this._rotMatrix.m[14] = 0;
  51870. this._rotMatrix.m[15] = 1.0;
  51871. };
  51872. /**
  51873. * Disposes the SPS.
  51874. */
  51875. SolidParticleSystem.prototype.dispose = function () {
  51876. this.mesh.dispose();
  51877. this.vars = null;
  51878. // drop references to internal big arrays for the GC
  51879. this._positions = null;
  51880. this._indices = null;
  51881. this._normals = null;
  51882. this._uvs = null;
  51883. this._colors = null;
  51884. this._indices32 = null;
  51885. this._positions32 = null;
  51886. this._normals32 = null;
  51887. this._fixedNormal32 = null;
  51888. this._uvs32 = null;
  51889. this._colors32 = null;
  51890. this.pickedParticles = null;
  51891. };
  51892. /**
  51893. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  51894. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  51895. * @returns the SPS.
  51896. */
  51897. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  51898. if (!this._isVisibilityBoxLocked) {
  51899. this.mesh.refreshBoundingInfo();
  51900. }
  51901. return this;
  51902. };
  51903. /**
  51904. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  51905. * @param size the size (float) of the visibility box
  51906. * note : this doesn't lock the SPS mesh bounding box.
  51907. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  51908. */
  51909. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  51910. var vis = size / 2;
  51911. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  51912. };
  51913. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  51914. /**
  51915. * Gets whether the SPS as always visible or not
  51916. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  51917. */
  51918. get: function () {
  51919. return this._alwaysVisible;
  51920. },
  51921. /**
  51922. * Sets the SPS as always visible or not
  51923. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  51924. */
  51925. set: function (val) {
  51926. this._alwaysVisible = val;
  51927. this.mesh.alwaysSelectAsActiveMesh = val;
  51928. },
  51929. enumerable: true,
  51930. configurable: true
  51931. });
  51932. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  51933. /**
  51934. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  51935. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  51936. */
  51937. get: function () {
  51938. return this._isVisibilityBoxLocked;
  51939. },
  51940. /**
  51941. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  51942. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  51943. */
  51944. set: function (val) {
  51945. this._isVisibilityBoxLocked = val;
  51946. var boundingInfo = this.mesh.getBoundingInfo();
  51947. boundingInfo.isLocked = val;
  51948. },
  51949. enumerable: true,
  51950. configurable: true
  51951. });
  51952. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  51953. /**
  51954. * Gets if `setParticles()` computes the particle rotations or not.
  51955. * Default value : true. The SPS is faster when it's set to false.
  51956. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  51957. */
  51958. get: function () {
  51959. return this._computeParticleRotation;
  51960. },
  51961. /**
  51962. * Tells to `setParticles()` to compute the particle rotations or not.
  51963. * Default value : true. The SPS is faster when it's set to false.
  51964. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  51965. */
  51966. set: function (val) {
  51967. this._computeParticleRotation = val;
  51968. },
  51969. enumerable: true,
  51970. configurable: true
  51971. });
  51972. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  51973. /**
  51974. * Gets if `setParticles()` computes the particle colors or not.
  51975. * Default value : true. The SPS is faster when it's set to false.
  51976. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  51977. */
  51978. get: function () {
  51979. return this._computeParticleColor;
  51980. },
  51981. /**
  51982. * Tells to `setParticles()` to compute the particle colors or not.
  51983. * Default value : true. The SPS is faster when it's set to false.
  51984. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  51985. */
  51986. set: function (val) {
  51987. this._computeParticleColor = val;
  51988. },
  51989. enumerable: true,
  51990. configurable: true
  51991. });
  51992. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  51993. /**
  51994. * Gets if `setParticles()` computes the particle textures or not.
  51995. * Default value : true. The SPS is faster when it's set to false.
  51996. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  51997. */
  51998. get: function () {
  51999. return this._computeParticleTexture;
  52000. },
  52001. set: function (val) {
  52002. this._computeParticleTexture = val;
  52003. },
  52004. enumerable: true,
  52005. configurable: true
  52006. });
  52007. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  52008. /**
  52009. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  52010. * Default value : false. The SPS is faster when it's set to false.
  52011. * Note : the particle custom vertex positions aren't stored values.
  52012. */
  52013. get: function () {
  52014. return this._computeParticleVertex;
  52015. },
  52016. /**
  52017. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  52018. * Default value : false. The SPS is faster when it's set to false.
  52019. * Note : the particle custom vertex positions aren't stored values.
  52020. */
  52021. set: function (val) {
  52022. this._computeParticleVertex = val;
  52023. },
  52024. enumerable: true,
  52025. configurable: true
  52026. });
  52027. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  52028. /**
  52029. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  52030. */
  52031. get: function () {
  52032. return this._computeBoundingBox;
  52033. },
  52034. /**
  52035. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  52036. */
  52037. set: function (val) {
  52038. this._computeBoundingBox = val;
  52039. },
  52040. enumerable: true,
  52041. configurable: true
  52042. });
  52043. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  52044. /**
  52045. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  52046. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  52047. * Default : `true`
  52048. */
  52049. get: function () {
  52050. return this._depthSortParticles;
  52051. },
  52052. /**
  52053. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  52054. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  52055. * Default : `true`
  52056. */
  52057. set: function (val) {
  52058. this._depthSortParticles = val;
  52059. },
  52060. enumerable: true,
  52061. configurable: true
  52062. });
  52063. // =======================================================================
  52064. // Particle behavior logic
  52065. // these following methods may be overwritten by the user to fit his needs
  52066. /**
  52067. * This function does nothing. It may be overwritten to set all the particle first values.
  52068. * The SPS doesn't call this function, you may have to call it by your own.
  52069. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52070. */
  52071. SolidParticleSystem.prototype.initParticles = function () {
  52072. };
  52073. /**
  52074. * This function does nothing. It may be overwritten to recycle a particle.
  52075. * The SPS doesn't call this function, you may have to call it by your own.
  52076. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52077. * @param particle The particle to recycle
  52078. * @returns the recycled particle
  52079. */
  52080. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  52081. return particle;
  52082. };
  52083. /**
  52084. * Updates a particle : this function should be overwritten by the user.
  52085. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  52086. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52087. * @example : just set a particle position or velocity and recycle conditions
  52088. * @param particle The particle to update
  52089. * @returns the updated particle
  52090. */
  52091. SolidParticleSystem.prototype.updateParticle = function (particle) {
  52092. return particle;
  52093. };
  52094. /**
  52095. * Updates a vertex of a particle : it can be overwritten by the user.
  52096. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  52097. * @param particle the current particle
  52098. * @param vertex the current index of the current particle
  52099. * @param pt the index of the current vertex in the particle shape
  52100. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  52101. * @example : just set a vertex particle position
  52102. * @returns the updated vertex
  52103. */
  52104. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  52105. return vertex;
  52106. };
  52107. /**
  52108. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  52109. * This does nothing and may be overwritten by the user.
  52110. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52111. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52112. * @param update the boolean update value actually passed to setParticles()
  52113. */
  52114. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  52115. };
  52116. /**
  52117. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  52118. * This will be passed three parameters.
  52119. * This does nothing and may be overwritten by the user.
  52120. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52121. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52122. * @param update the boolean update value actually passed to setParticles()
  52123. */
  52124. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  52125. };
  52126. return SolidParticleSystem;
  52127. }());
  52128. BABYLON.SolidParticleSystem = SolidParticleSystem;
  52129. })(BABYLON || (BABYLON = {}));
  52130. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  52131. var BABYLON;
  52132. (function (BABYLON) {
  52133. var ShaderMaterial = /** @class */ (function (_super) {
  52134. __extends(ShaderMaterial, _super);
  52135. function ShaderMaterial(name, scene, shaderPath, options) {
  52136. var _this = _super.call(this, name, scene) || this;
  52137. _this._textures = {};
  52138. _this._textureArrays = {};
  52139. _this._floats = {};
  52140. _this._ints = {};
  52141. _this._floatsArrays = {};
  52142. _this._colors3 = {};
  52143. _this._colors3Arrays = {};
  52144. _this._colors4 = {};
  52145. _this._vectors2 = {};
  52146. _this._vectors3 = {};
  52147. _this._vectors4 = {};
  52148. _this._matrices = {};
  52149. _this._matrices3x3 = {};
  52150. _this._matrices2x2 = {};
  52151. _this._vectors2Arrays = {};
  52152. _this._vectors3Arrays = {};
  52153. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  52154. _this._shaderPath = shaderPath;
  52155. options.needAlphaBlending = options.needAlphaBlending || false;
  52156. options.needAlphaTesting = options.needAlphaTesting || false;
  52157. options.attributes = options.attributes || ["position", "normal", "uv"];
  52158. options.uniforms = options.uniforms || ["worldViewProjection"];
  52159. options.uniformBuffers = options.uniformBuffers || [];
  52160. options.samplers = options.samplers || [];
  52161. options.defines = options.defines || [];
  52162. _this._options = options;
  52163. return _this;
  52164. }
  52165. ShaderMaterial.prototype.getClassName = function () {
  52166. return "ShaderMaterial";
  52167. };
  52168. ShaderMaterial.prototype.needAlphaBlending = function () {
  52169. return this._options.needAlphaBlending;
  52170. };
  52171. ShaderMaterial.prototype.needAlphaTesting = function () {
  52172. return this._options.needAlphaTesting;
  52173. };
  52174. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  52175. if (this._options.uniforms.indexOf(uniformName) === -1) {
  52176. this._options.uniforms.push(uniformName);
  52177. }
  52178. };
  52179. ShaderMaterial.prototype.setTexture = function (name, texture) {
  52180. if (this._options.samplers.indexOf(name) === -1) {
  52181. this._options.samplers.push(name);
  52182. }
  52183. this._textures[name] = texture;
  52184. return this;
  52185. };
  52186. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  52187. if (this._options.samplers.indexOf(name) === -1) {
  52188. this._options.samplers.push(name);
  52189. }
  52190. this._checkUniform(name);
  52191. this._textureArrays[name] = textures;
  52192. return this;
  52193. };
  52194. ShaderMaterial.prototype.setFloat = function (name, value) {
  52195. this._checkUniform(name);
  52196. this._floats[name] = value;
  52197. return this;
  52198. };
  52199. ShaderMaterial.prototype.setInt = function (name, value) {
  52200. this._checkUniform(name);
  52201. this._ints[name] = value;
  52202. return this;
  52203. };
  52204. ShaderMaterial.prototype.setFloats = function (name, value) {
  52205. this._checkUniform(name);
  52206. this._floatsArrays[name] = value;
  52207. return this;
  52208. };
  52209. ShaderMaterial.prototype.setColor3 = function (name, value) {
  52210. this._checkUniform(name);
  52211. this._colors3[name] = value;
  52212. return this;
  52213. };
  52214. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  52215. this._checkUniform(name);
  52216. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  52217. color.toArray(arr, arr.length);
  52218. return arr;
  52219. }, []);
  52220. return this;
  52221. };
  52222. ShaderMaterial.prototype.setColor4 = function (name, value) {
  52223. this._checkUniform(name);
  52224. this._colors4[name] = value;
  52225. return this;
  52226. };
  52227. ShaderMaterial.prototype.setVector2 = function (name, value) {
  52228. this._checkUniform(name);
  52229. this._vectors2[name] = value;
  52230. return this;
  52231. };
  52232. ShaderMaterial.prototype.setVector3 = function (name, value) {
  52233. this._checkUniform(name);
  52234. this._vectors3[name] = value;
  52235. return this;
  52236. };
  52237. ShaderMaterial.prototype.setVector4 = function (name, value) {
  52238. this._checkUniform(name);
  52239. this._vectors4[name] = value;
  52240. return this;
  52241. };
  52242. ShaderMaterial.prototype.setMatrix = function (name, value) {
  52243. this._checkUniform(name);
  52244. this._matrices[name] = value;
  52245. return this;
  52246. };
  52247. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  52248. this._checkUniform(name);
  52249. this._matrices3x3[name] = value;
  52250. return this;
  52251. };
  52252. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  52253. this._checkUniform(name);
  52254. this._matrices2x2[name] = value;
  52255. return this;
  52256. };
  52257. ShaderMaterial.prototype.setArray2 = function (name, value) {
  52258. this._checkUniform(name);
  52259. this._vectors2Arrays[name] = value;
  52260. return this;
  52261. };
  52262. ShaderMaterial.prototype.setArray3 = function (name, value) {
  52263. this._checkUniform(name);
  52264. this._vectors3Arrays[name] = value;
  52265. return this;
  52266. };
  52267. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  52268. if (!mesh) {
  52269. return true;
  52270. }
  52271. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  52272. return false;
  52273. }
  52274. return false;
  52275. };
  52276. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  52277. var scene = this.getScene();
  52278. var engine = scene.getEngine();
  52279. if (!this.checkReadyOnEveryCall) {
  52280. if (this._renderId === scene.getRenderId()) {
  52281. if (this._checkCache(scene, mesh, useInstances)) {
  52282. return true;
  52283. }
  52284. }
  52285. }
  52286. // Instances
  52287. var defines = [];
  52288. var attribs = [];
  52289. var fallbacks = new BABYLON.EffectFallbacks();
  52290. if (useInstances) {
  52291. defines.push("#define INSTANCES");
  52292. }
  52293. for (var index = 0; index < this._options.defines.length; index++) {
  52294. defines.push(this._options.defines[index]);
  52295. }
  52296. for (var index = 0; index < this._options.attributes.length; index++) {
  52297. attribs.push(this._options.attributes[index]);
  52298. }
  52299. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  52300. attribs.push(BABYLON.VertexBuffer.ColorKind);
  52301. defines.push("#define VERTEXCOLOR");
  52302. }
  52303. // Bones
  52304. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  52305. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52306. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52307. if (mesh.numBoneInfluencers > 4) {
  52308. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52309. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52310. }
  52311. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52312. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52313. fallbacks.addCPUSkinningFallback(0, mesh);
  52314. if (this._options.uniforms.indexOf("mBones") === -1) {
  52315. this._options.uniforms.push("mBones");
  52316. }
  52317. }
  52318. else {
  52319. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52320. }
  52321. // Textures
  52322. for (var name in this._textures) {
  52323. if (!this._textures[name].isReady()) {
  52324. return false;
  52325. }
  52326. }
  52327. // Alpha test
  52328. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  52329. defines.push("#define ALPHATEST");
  52330. }
  52331. var previousEffect = this._effect;
  52332. var join = defines.join("\n");
  52333. this._effect = engine.createEffect(this._shaderPath, {
  52334. attributes: attribs,
  52335. uniformsNames: this._options.uniforms,
  52336. uniformBuffersNames: this._options.uniformBuffers,
  52337. samplers: this._options.samplers,
  52338. defines: join,
  52339. fallbacks: fallbacks,
  52340. onCompiled: this.onCompiled,
  52341. onError: this.onError
  52342. }, engine);
  52343. if (!this._effect.isReady()) {
  52344. return false;
  52345. }
  52346. if (previousEffect !== this._effect) {
  52347. scene.resetCachedMaterial();
  52348. }
  52349. this._renderId = scene.getRenderId();
  52350. return true;
  52351. };
  52352. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  52353. var scene = this.getScene();
  52354. if (!this._effect) {
  52355. return;
  52356. }
  52357. if (this._options.uniforms.indexOf("world") !== -1) {
  52358. this._effect.setMatrix("world", world);
  52359. }
  52360. if (this._options.uniforms.indexOf("worldView") !== -1) {
  52361. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  52362. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  52363. }
  52364. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  52365. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  52366. }
  52367. };
  52368. ShaderMaterial.prototype.bind = function (world, mesh) {
  52369. // Std values
  52370. this.bindOnlyWorldMatrix(world);
  52371. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  52372. if (this._options.uniforms.indexOf("view") !== -1) {
  52373. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  52374. }
  52375. if (this._options.uniforms.indexOf("projection") !== -1) {
  52376. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  52377. }
  52378. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  52379. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  52380. }
  52381. // Bones
  52382. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  52383. var name;
  52384. // Texture
  52385. for (name in this._textures) {
  52386. this._effect.setTexture(name, this._textures[name]);
  52387. }
  52388. // Texture arrays
  52389. for (name in this._textureArrays) {
  52390. this._effect.setTextureArray(name, this._textureArrays[name]);
  52391. }
  52392. // Int
  52393. for (name in this._ints) {
  52394. this._effect.setInt(name, this._ints[name]);
  52395. }
  52396. // Float
  52397. for (name in this._floats) {
  52398. this._effect.setFloat(name, this._floats[name]);
  52399. }
  52400. // Floats
  52401. for (name in this._floatsArrays) {
  52402. this._effect.setArray(name, this._floatsArrays[name]);
  52403. }
  52404. // Color3
  52405. for (name in this._colors3) {
  52406. this._effect.setColor3(name, this._colors3[name]);
  52407. }
  52408. for (name in this._colors3Arrays) {
  52409. this._effect.setArray3(name, this._colors3Arrays[name]);
  52410. }
  52411. // Color4
  52412. for (name in this._colors4) {
  52413. var color = this._colors4[name];
  52414. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  52415. }
  52416. // Vector2
  52417. for (name in this._vectors2) {
  52418. this._effect.setVector2(name, this._vectors2[name]);
  52419. }
  52420. // Vector3
  52421. for (name in this._vectors3) {
  52422. this._effect.setVector3(name, this._vectors3[name]);
  52423. }
  52424. // Vector4
  52425. for (name in this._vectors4) {
  52426. this._effect.setVector4(name, this._vectors4[name]);
  52427. }
  52428. // Matrix
  52429. for (name in this._matrices) {
  52430. this._effect.setMatrix(name, this._matrices[name]);
  52431. }
  52432. // Matrix 3x3
  52433. for (name in this._matrices3x3) {
  52434. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  52435. }
  52436. // Matrix 2x2
  52437. for (name in this._matrices2x2) {
  52438. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  52439. }
  52440. // Vector2Array
  52441. for (name in this._vectors2Arrays) {
  52442. this._effect.setArray2(name, this._vectors2Arrays[name]);
  52443. }
  52444. // Vector3Array
  52445. for (name in this._vectors3Arrays) {
  52446. this._effect.setArray3(name, this._vectors3Arrays[name]);
  52447. }
  52448. }
  52449. this._afterBind(mesh);
  52450. };
  52451. ShaderMaterial.prototype.getActiveTextures = function () {
  52452. var activeTextures = _super.prototype.getActiveTextures.call(this);
  52453. for (var name in this._textures) {
  52454. activeTextures.push(this._textures[name]);
  52455. }
  52456. for (var name in this._textureArrays) {
  52457. var array = this._textureArrays[name];
  52458. for (var index = 0; index < array.length; index++) {
  52459. activeTextures.push(array[index]);
  52460. }
  52461. }
  52462. return activeTextures;
  52463. };
  52464. ShaderMaterial.prototype.hasTexture = function (texture) {
  52465. if (_super.prototype.hasTexture.call(this, texture)) {
  52466. return true;
  52467. }
  52468. for (var name in this._textures) {
  52469. if (this._textures[name] === texture) {
  52470. return true;
  52471. }
  52472. }
  52473. for (var name in this._textureArrays) {
  52474. var array = this._textureArrays[name];
  52475. for (var index = 0; index < array.length; index++) {
  52476. if (array[index] === texture) {
  52477. return true;
  52478. }
  52479. }
  52480. }
  52481. return false;
  52482. };
  52483. ShaderMaterial.prototype.clone = function (name) {
  52484. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  52485. return newShaderMaterial;
  52486. };
  52487. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  52488. if (forceDisposeTextures) {
  52489. var name;
  52490. for (name in this._textures) {
  52491. this._textures[name].dispose();
  52492. }
  52493. for (name in this._textureArrays) {
  52494. var array = this._textureArrays[name];
  52495. for (var index = 0; index < array.length; index++) {
  52496. array[index].dispose();
  52497. }
  52498. }
  52499. }
  52500. this._textures = {};
  52501. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  52502. };
  52503. ShaderMaterial.prototype.serialize = function () {
  52504. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  52505. serializationObject.customType = "BABYLON.ShaderMaterial";
  52506. serializationObject.options = this._options;
  52507. serializationObject.shaderPath = this._shaderPath;
  52508. var name;
  52509. // Texture
  52510. serializationObject.textures = {};
  52511. for (name in this._textures) {
  52512. serializationObject.textures[name] = this._textures[name].serialize();
  52513. }
  52514. // Texture arrays
  52515. serializationObject.textureArrays = {};
  52516. for (name in this._textureArrays) {
  52517. serializationObject.textureArrays[name] = [];
  52518. var array = this._textureArrays[name];
  52519. for (var index = 0; index < array.length; index++) {
  52520. serializationObject.textureArrays[name].push(array[index].serialize());
  52521. }
  52522. }
  52523. // Float
  52524. serializationObject.floats = {};
  52525. for (name in this._floats) {
  52526. serializationObject.floats[name] = this._floats[name];
  52527. }
  52528. // Float s
  52529. serializationObject.FloatArrays = {};
  52530. for (name in this._floatsArrays) {
  52531. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  52532. }
  52533. // Color3
  52534. serializationObject.colors3 = {};
  52535. for (name in this._colors3) {
  52536. serializationObject.colors3[name] = this._colors3[name].asArray();
  52537. }
  52538. // Color3 array
  52539. serializationObject.colors3Arrays = {};
  52540. for (name in this._colors3Arrays) {
  52541. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  52542. }
  52543. // Color4
  52544. serializationObject.colors4 = {};
  52545. for (name in this._colors4) {
  52546. serializationObject.colors4[name] = this._colors4[name].asArray();
  52547. }
  52548. // Vector2
  52549. serializationObject.vectors2 = {};
  52550. for (name in this._vectors2) {
  52551. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  52552. }
  52553. // Vector3
  52554. serializationObject.vectors3 = {};
  52555. for (name in this._vectors3) {
  52556. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  52557. }
  52558. // Vector4
  52559. serializationObject.vectors4 = {};
  52560. for (name in this._vectors4) {
  52561. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  52562. }
  52563. // Matrix
  52564. serializationObject.matrices = {};
  52565. for (name in this._matrices) {
  52566. serializationObject.matrices[name] = this._matrices[name].asArray();
  52567. }
  52568. // Matrix 3x3
  52569. serializationObject.matrices3x3 = {};
  52570. for (name in this._matrices3x3) {
  52571. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  52572. }
  52573. // Matrix 2x2
  52574. serializationObject.matrices2x2 = {};
  52575. for (name in this._matrices2x2) {
  52576. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  52577. }
  52578. // Vector2Array
  52579. serializationObject.vectors2Arrays = {};
  52580. for (name in this._vectors2Arrays) {
  52581. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  52582. }
  52583. // Vector3Array
  52584. serializationObject.vectors3Arrays = {};
  52585. for (name in this._vectors3Arrays) {
  52586. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  52587. }
  52588. return serializationObject;
  52589. };
  52590. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  52591. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  52592. var name;
  52593. // Texture
  52594. for (name in source.textures) {
  52595. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  52596. }
  52597. // Texture arrays
  52598. for (name in source.textureArrays) {
  52599. var array = source.textureArrays[name];
  52600. var textureArray = new Array();
  52601. for (var index = 0; index < array.length; index++) {
  52602. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  52603. }
  52604. material.setTextureArray(name, textureArray);
  52605. }
  52606. // Float
  52607. for (name in source.floats) {
  52608. material.setFloat(name, source.floats[name]);
  52609. }
  52610. // Float s
  52611. for (name in source.floatsArrays) {
  52612. material.setFloats(name, source.floatsArrays[name]);
  52613. }
  52614. // Color3
  52615. for (name in source.colors3) {
  52616. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  52617. }
  52618. // Color3 arrays
  52619. for (name in source.colors3Arrays) {
  52620. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  52621. if (i % 3 === 0) {
  52622. arr.push([num]);
  52623. }
  52624. else {
  52625. arr[arr.length - 1].push(num);
  52626. }
  52627. return arr;
  52628. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  52629. material.setColor3Array(name, colors);
  52630. }
  52631. // Color4
  52632. for (name in source.colors4) {
  52633. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  52634. }
  52635. // Vector2
  52636. for (name in source.vectors2) {
  52637. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  52638. }
  52639. // Vector3
  52640. for (name in source.vectors3) {
  52641. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  52642. }
  52643. // Vector4
  52644. for (name in source.vectors4) {
  52645. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  52646. }
  52647. // Matrix
  52648. for (name in source.matrices) {
  52649. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  52650. }
  52651. // Matrix 3x3
  52652. for (name in source.matrices3x3) {
  52653. material.setMatrix3x3(name, source.matrices3x3[name]);
  52654. }
  52655. // Matrix 2x2
  52656. for (name in source.matrices2x2) {
  52657. material.setMatrix2x2(name, source.matrices2x2[name]);
  52658. }
  52659. // Vector2Array
  52660. for (name in source.vectors2Arrays) {
  52661. material.setArray2(name, source.vectors2Arrays[name]);
  52662. }
  52663. // Vector3Array
  52664. for (name in source.vectors3Arrays) {
  52665. material.setArray3(name, source.vectors3Arrays[name]);
  52666. }
  52667. return material;
  52668. };
  52669. return ShaderMaterial;
  52670. }(BABYLON.Material));
  52671. BABYLON.ShaderMaterial = ShaderMaterial;
  52672. })(BABYLON || (BABYLON = {}));
  52673. //# sourceMappingURL=babylon.shaderMaterial.js.map
  52674. var BABYLON;
  52675. (function (BABYLON) {
  52676. var GroundMesh = /** @class */ (function (_super) {
  52677. __extends(GroundMesh, _super);
  52678. function GroundMesh(name, scene) {
  52679. var _this = _super.call(this, name, scene) || this;
  52680. _this.generateOctree = false;
  52681. return _this;
  52682. }
  52683. GroundMesh.prototype.getClassName = function () {
  52684. return "GroundMesh";
  52685. };
  52686. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  52687. get: function () {
  52688. return Math.min(this._subdivisionsX, this._subdivisionsY);
  52689. },
  52690. enumerable: true,
  52691. configurable: true
  52692. });
  52693. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  52694. get: function () {
  52695. return this._subdivisionsX;
  52696. },
  52697. enumerable: true,
  52698. configurable: true
  52699. });
  52700. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  52701. get: function () {
  52702. return this._subdivisionsY;
  52703. },
  52704. enumerable: true,
  52705. configurable: true
  52706. });
  52707. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  52708. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  52709. this._subdivisionsX = chunksCount;
  52710. this._subdivisionsY = chunksCount;
  52711. this.subdivide(chunksCount);
  52712. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  52713. };
  52714. /**
  52715. * Returns a height (y) value in the Worl system :
  52716. * the ground altitude at the coordinates (x, z) expressed in the World system.
  52717. * Returns the ground y position if (x, z) are outside the ground surface.
  52718. */
  52719. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  52720. var world = this.getWorldMatrix();
  52721. var invMat = BABYLON.Tmp.Matrix[5];
  52722. world.invertToRef(invMat);
  52723. var tmpVect = BABYLON.Tmp.Vector3[8];
  52724. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  52725. x = tmpVect.x;
  52726. z = tmpVect.z;
  52727. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  52728. return this.position.y;
  52729. }
  52730. if (!this._heightQuads || this._heightQuads.length == 0) {
  52731. this._initHeightQuads();
  52732. this._computeHeightQuads();
  52733. }
  52734. var facet = this._getFacetAt(x, z);
  52735. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  52736. // return y in the World system
  52737. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  52738. return tmpVect.y;
  52739. };
  52740. /**
  52741. * Returns a normalized vector (Vector3) orthogonal to the ground
  52742. * at the ground coordinates (x, z) expressed in the World system.
  52743. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  52744. */
  52745. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  52746. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  52747. this.getNormalAtCoordinatesToRef(x, z, normal);
  52748. return normal;
  52749. };
  52750. /**
  52751. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  52752. * at the ground coordinates (x, z) expressed in the World system.
  52753. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  52754. * Returns the GroundMesh.
  52755. */
  52756. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  52757. var world = this.getWorldMatrix();
  52758. var tmpMat = BABYLON.Tmp.Matrix[5];
  52759. world.invertToRef(tmpMat);
  52760. var tmpVect = BABYLON.Tmp.Vector3[8];
  52761. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  52762. x = tmpVect.x;
  52763. z = tmpVect.z;
  52764. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  52765. return this;
  52766. }
  52767. if (!this._heightQuads || this._heightQuads.length == 0) {
  52768. this._initHeightQuads();
  52769. this._computeHeightQuads();
  52770. }
  52771. var facet = this._getFacetAt(x, z);
  52772. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  52773. return this;
  52774. };
  52775. /**
  52776. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  52777. * if the ground has been updated.
  52778. * This can be used in the render loop.
  52779. * Returns the GroundMesh.
  52780. */
  52781. GroundMesh.prototype.updateCoordinateHeights = function () {
  52782. if (!this._heightQuads || this._heightQuads.length == 0) {
  52783. this._initHeightQuads();
  52784. }
  52785. this._computeHeightQuads();
  52786. return this;
  52787. };
  52788. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  52789. GroundMesh.prototype._getFacetAt = function (x, z) {
  52790. // retrieve col and row from x, z coordinates in the ground local system
  52791. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  52792. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  52793. var quad = this._heightQuads[row * this._subdivisionsX + col];
  52794. var facet;
  52795. if (z < quad.slope.x * x + quad.slope.y) {
  52796. facet = quad.facet1;
  52797. }
  52798. else {
  52799. facet = quad.facet2;
  52800. }
  52801. return facet;
  52802. };
  52803. // Creates and populates the heightMap array with "facet" elements :
  52804. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  52805. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  52806. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  52807. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  52808. // Returns the GroundMesh.
  52809. GroundMesh.prototype._initHeightQuads = function () {
  52810. var subdivisionsX = this._subdivisionsX;
  52811. var subdivisionsY = this._subdivisionsY;
  52812. this._heightQuads = new Array();
  52813. for (var row = 0; row < subdivisionsY; row++) {
  52814. for (var col = 0; col < subdivisionsX; col++) {
  52815. 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) };
  52816. this._heightQuads[row * subdivisionsX + col] = quad;
  52817. }
  52818. }
  52819. return this;
  52820. };
  52821. // Compute each quad element values and update the the heightMap array :
  52822. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  52823. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  52824. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  52825. // Returns the GroundMesh.
  52826. GroundMesh.prototype._computeHeightQuads = function () {
  52827. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52828. if (!positions) {
  52829. return this;
  52830. }
  52831. var v1 = BABYLON.Tmp.Vector3[3];
  52832. var v2 = BABYLON.Tmp.Vector3[2];
  52833. var v3 = BABYLON.Tmp.Vector3[1];
  52834. var v4 = BABYLON.Tmp.Vector3[0];
  52835. var v1v2 = BABYLON.Tmp.Vector3[4];
  52836. var v1v3 = BABYLON.Tmp.Vector3[5];
  52837. var v1v4 = BABYLON.Tmp.Vector3[6];
  52838. var norm1 = BABYLON.Tmp.Vector3[7];
  52839. var norm2 = BABYLON.Tmp.Vector3[8];
  52840. var i = 0;
  52841. var j = 0;
  52842. var k = 0;
  52843. var cd = 0; // 2D slope coefficient : z = cd * x + h
  52844. var h = 0;
  52845. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  52846. var d2 = 0;
  52847. var subdivisionsX = this._subdivisionsX;
  52848. var subdivisionsY = this._subdivisionsY;
  52849. for (var row = 0; row < subdivisionsY; row++) {
  52850. for (var col = 0; col < subdivisionsX; col++) {
  52851. i = col * 3;
  52852. j = row * (subdivisionsX + 1) * 3;
  52853. k = (row + 1) * (subdivisionsX + 1) * 3;
  52854. v1.x = positions[j + i];
  52855. v1.y = positions[j + i + 1];
  52856. v1.z = positions[j + i + 2];
  52857. v2.x = positions[j + i + 3];
  52858. v2.y = positions[j + i + 4];
  52859. v2.z = positions[j + i + 5];
  52860. v3.x = positions[k + i];
  52861. v3.y = positions[k + i + 1];
  52862. v3.z = positions[k + i + 2];
  52863. v4.x = positions[k + i + 3];
  52864. v4.y = positions[k + i + 4];
  52865. v4.z = positions[k + i + 5];
  52866. // 2D slope V1V4
  52867. cd = (v4.z - v1.z) / (v4.x - v1.x);
  52868. h = v1.z - cd * v1.x; // v1 belongs to the slope
  52869. // facet equations :
  52870. // we compute each facet normal vector
  52871. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  52872. // we compute the value d by applying the equation to v1 which belongs to the plane
  52873. // then we store the facet equation in a Vector4
  52874. v2.subtractToRef(v1, v1v2);
  52875. v3.subtractToRef(v1, v1v3);
  52876. v4.subtractToRef(v1, v1v4);
  52877. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  52878. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  52879. norm1.normalize();
  52880. norm2.normalize();
  52881. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  52882. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  52883. var quad = this._heightQuads[row * subdivisionsX + col];
  52884. quad.slope.copyFromFloats(cd, h);
  52885. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  52886. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  52887. }
  52888. }
  52889. return this;
  52890. };
  52891. GroundMesh.prototype.serialize = function (serializationObject) {
  52892. _super.prototype.serialize.call(this, serializationObject);
  52893. serializationObject.subdivisionsX = this._subdivisionsX;
  52894. serializationObject.subdivisionsY = this._subdivisionsY;
  52895. serializationObject.minX = this._minX;
  52896. serializationObject.maxX = this._maxX;
  52897. serializationObject.minZ = this._minZ;
  52898. serializationObject.maxZ = this._maxZ;
  52899. serializationObject.width = this._width;
  52900. serializationObject.height = this._height;
  52901. };
  52902. GroundMesh.Parse = function (parsedMesh, scene) {
  52903. var result = new GroundMesh(parsedMesh.name, scene);
  52904. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  52905. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  52906. result._minX = parsedMesh.minX;
  52907. result._maxX = parsedMesh.maxX;
  52908. result._minZ = parsedMesh.minZ;
  52909. result._maxZ = parsedMesh.maxZ;
  52910. result._width = parsedMesh.width;
  52911. result._height = parsedMesh.height;
  52912. return result;
  52913. };
  52914. return GroundMesh;
  52915. }(BABYLON.Mesh));
  52916. BABYLON.GroundMesh = GroundMesh;
  52917. })(BABYLON || (BABYLON = {}));
  52918. //# sourceMappingURL=babylon.groundMesh.js.map
  52919. var BABYLON;
  52920. (function (BABYLON) {
  52921. /**
  52922. * Creates an instance based on a source mesh.
  52923. */
  52924. var InstancedMesh = /** @class */ (function (_super) {
  52925. __extends(InstancedMesh, _super);
  52926. function InstancedMesh(name, source) {
  52927. var _this = _super.call(this, name, source.getScene()) || this;
  52928. source.instances.push(_this);
  52929. _this._sourceMesh = source;
  52930. _this.position.copyFrom(source.position);
  52931. _this.rotation.copyFrom(source.rotation);
  52932. _this.scaling.copyFrom(source.scaling);
  52933. if (source.rotationQuaternion) {
  52934. _this.rotationQuaternion = source.rotationQuaternion.clone();
  52935. }
  52936. _this.infiniteDistance = source.infiniteDistance;
  52937. _this.setPivotMatrix(source.getPivotMatrix());
  52938. _this.refreshBoundingInfo();
  52939. _this._syncSubMeshes();
  52940. return _this;
  52941. }
  52942. /**
  52943. * Returns the string "InstancedMesh".
  52944. */
  52945. InstancedMesh.prototype.getClassName = function () {
  52946. return "InstancedMesh";
  52947. };
  52948. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  52949. // Methods
  52950. get: function () {
  52951. return this._sourceMesh.receiveShadows;
  52952. },
  52953. enumerable: true,
  52954. configurable: true
  52955. });
  52956. Object.defineProperty(InstancedMesh.prototype, "material", {
  52957. get: function () {
  52958. return this._sourceMesh.material;
  52959. },
  52960. enumerable: true,
  52961. configurable: true
  52962. });
  52963. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  52964. get: function () {
  52965. return this._sourceMesh.visibility;
  52966. },
  52967. enumerable: true,
  52968. configurable: true
  52969. });
  52970. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  52971. get: function () {
  52972. return this._sourceMesh.skeleton;
  52973. },
  52974. enumerable: true,
  52975. configurable: true
  52976. });
  52977. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  52978. get: function () {
  52979. return this._sourceMesh.renderingGroupId;
  52980. },
  52981. enumerable: true,
  52982. configurable: true
  52983. });
  52984. /**
  52985. * Returns the total number of vertices (integer).
  52986. */
  52987. InstancedMesh.prototype.getTotalVertices = function () {
  52988. return this._sourceMesh.getTotalVertices();
  52989. };
  52990. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  52991. get: function () {
  52992. return this._sourceMesh;
  52993. },
  52994. enumerable: true,
  52995. configurable: true
  52996. });
  52997. /**
  52998. * Is this node ready to be used/rendered
  52999. * @return {boolean} is it ready
  53000. */
  53001. InstancedMesh.prototype.isReady = function () {
  53002. return this._sourceMesh.isReady(true);
  53003. };
  53004. /**
  53005. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  53006. */
  53007. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  53008. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  53009. };
  53010. /**
  53011. * Sets the vertex data of the mesh geometry for the requested `kind`.
  53012. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  53013. * The `data` are either a numeric array either a Float32Array.
  53014. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  53015. * 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).
  53016. * Note that a new underlying VertexBuffer object is created each call.
  53017. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  53018. *
  53019. * Possible `kind` values :
  53020. * - BABYLON.VertexBuffer.PositionKind
  53021. * - BABYLON.VertexBuffer.UVKind
  53022. * - BABYLON.VertexBuffer.UV2Kind
  53023. * - BABYLON.VertexBuffer.UV3Kind
  53024. * - BABYLON.VertexBuffer.UV4Kind
  53025. * - BABYLON.VertexBuffer.UV5Kind
  53026. * - BABYLON.VertexBuffer.UV6Kind
  53027. * - BABYLON.VertexBuffer.ColorKind
  53028. * - BABYLON.VertexBuffer.MatricesIndicesKind
  53029. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  53030. * - BABYLON.VertexBuffer.MatricesWeightsKind
  53031. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  53032. *
  53033. * Returns the Mesh.
  53034. */
  53035. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  53036. if (this.sourceMesh) {
  53037. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  53038. }
  53039. return this.sourceMesh;
  53040. };
  53041. /**
  53042. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  53043. * If the mesh has no geometry, it is simply returned as it is.
  53044. * The `data` are either a numeric array either a Float32Array.
  53045. * No new underlying VertexBuffer object is created.
  53046. * 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.
  53047. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  53048. *
  53049. * Possible `kind` values :
  53050. * - BABYLON.VertexBuffer.PositionKind
  53051. * - BABYLON.VertexBuffer.UVKind
  53052. * - BABYLON.VertexBuffer.UV2Kind
  53053. * - BABYLON.VertexBuffer.UV3Kind
  53054. * - BABYLON.VertexBuffer.UV4Kind
  53055. * - BABYLON.VertexBuffer.UV5Kind
  53056. * - BABYLON.VertexBuffer.UV6Kind
  53057. * - BABYLON.VertexBuffer.ColorKind
  53058. * - BABYLON.VertexBuffer.MatricesIndicesKind
  53059. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  53060. * - BABYLON.VertexBuffer.MatricesWeightsKind
  53061. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  53062. *
  53063. * Returns the Mesh.
  53064. */
  53065. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  53066. if (this.sourceMesh) {
  53067. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  53068. }
  53069. return this.sourceMesh;
  53070. };
  53071. /**
  53072. * Sets the mesh indices.
  53073. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  53074. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  53075. * This method creates a new index buffer each call.
  53076. * Returns the Mesh.
  53077. */
  53078. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  53079. if (totalVertices === void 0) { totalVertices = null; }
  53080. if (this.sourceMesh) {
  53081. this.sourceMesh.setIndices(indices, totalVertices);
  53082. }
  53083. return this.sourceMesh;
  53084. };
  53085. /**
  53086. * Boolean : True if the mesh owns the requested kind of data.
  53087. */
  53088. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  53089. return this._sourceMesh.isVerticesDataPresent(kind);
  53090. };
  53091. /**
  53092. * Returns an array of indices (IndicesArray).
  53093. */
  53094. InstancedMesh.prototype.getIndices = function () {
  53095. return this._sourceMesh.getIndices();
  53096. };
  53097. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  53098. get: function () {
  53099. return this._sourceMesh._positions;
  53100. },
  53101. enumerable: true,
  53102. configurable: true
  53103. });
  53104. /**
  53105. * Sets a new updated BoundingInfo to the mesh.
  53106. * Returns the mesh.
  53107. */
  53108. InstancedMesh.prototype.refreshBoundingInfo = function () {
  53109. var meshBB = this._sourceMesh.getBoundingInfo();
  53110. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  53111. this._updateBoundingInfo();
  53112. return this;
  53113. };
  53114. InstancedMesh.prototype._preActivate = function () {
  53115. if (this._currentLOD) {
  53116. this._currentLOD._preActivate();
  53117. }
  53118. return this;
  53119. };
  53120. InstancedMesh.prototype._activate = function (renderId) {
  53121. if (this._currentLOD) {
  53122. this._currentLOD._registerInstanceForRenderId(this, renderId);
  53123. }
  53124. return this;
  53125. };
  53126. /**
  53127. * Returns the current associated LOD AbstractMesh.
  53128. */
  53129. InstancedMesh.prototype.getLOD = function (camera) {
  53130. if (!camera) {
  53131. return this;
  53132. }
  53133. var boundingInfo = this.getBoundingInfo();
  53134. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  53135. if (this._currentLOD === this.sourceMesh) {
  53136. return this;
  53137. }
  53138. return this._currentLOD;
  53139. };
  53140. InstancedMesh.prototype._syncSubMeshes = function () {
  53141. this.releaseSubMeshes();
  53142. if (this._sourceMesh.subMeshes) {
  53143. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  53144. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  53145. }
  53146. }
  53147. return this;
  53148. };
  53149. InstancedMesh.prototype._generatePointsArray = function () {
  53150. return this._sourceMesh._generatePointsArray();
  53151. };
  53152. /**
  53153. * Creates a new InstancedMesh from the current mesh.
  53154. * - name (string) : the cloned mesh name
  53155. * - newParent (optional Node) : the optional Node to parent the clone to.
  53156. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  53157. *
  53158. * Returns the clone.
  53159. */
  53160. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  53161. var result = this._sourceMesh.createInstance(name);
  53162. // Deep copy
  53163. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  53164. // Bounding info
  53165. this.refreshBoundingInfo();
  53166. // Parent
  53167. if (newParent) {
  53168. result.parent = newParent;
  53169. }
  53170. if (!doNotCloneChildren) {
  53171. // Children
  53172. for (var index = 0; index < this.getScene().meshes.length; index++) {
  53173. var mesh = this.getScene().meshes[index];
  53174. if (mesh.parent === this) {
  53175. mesh.clone(mesh.name, result);
  53176. }
  53177. }
  53178. }
  53179. result.computeWorldMatrix(true);
  53180. return result;
  53181. };
  53182. /**
  53183. * Disposes the InstancedMesh.
  53184. * Returns nothing.
  53185. */
  53186. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  53187. // Remove from mesh
  53188. var index = this._sourceMesh.instances.indexOf(this);
  53189. this._sourceMesh.instances.splice(index, 1);
  53190. _super.prototype.dispose.call(this, doNotRecurse);
  53191. };
  53192. return InstancedMesh;
  53193. }(BABYLON.AbstractMesh));
  53194. BABYLON.InstancedMesh = InstancedMesh;
  53195. })(BABYLON || (BABYLON = {}));
  53196. //# sourceMappingURL=babylon.instancedMesh.js.map
  53197. var BABYLON;
  53198. (function (BABYLON) {
  53199. var LinesMesh = /** @class */ (function (_super) {
  53200. __extends(LinesMesh, _super);
  53201. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  53202. if (scene === void 0) { scene = null; }
  53203. if (parent === void 0) { parent = null; }
  53204. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  53205. _this.useVertexColor = useVertexColor;
  53206. _this.useVertexAlpha = useVertexAlpha;
  53207. _this.color = new BABYLON.Color3(1, 1, 1);
  53208. _this.alpha = 1;
  53209. if (source) {
  53210. _this.color = source.color.clone();
  53211. _this.alpha = source.alpha;
  53212. _this.useVertexColor = source.useVertexColor;
  53213. _this.useVertexAlpha = source.useVertexAlpha;
  53214. }
  53215. _this._intersectionThreshold = 0.1;
  53216. var defines = [];
  53217. var options = {
  53218. attributes: [BABYLON.VertexBuffer.PositionKind],
  53219. uniforms: ["world", "viewProjection"],
  53220. needAlphaBlending: true,
  53221. defines: defines
  53222. };
  53223. if (useVertexAlpha === false) {
  53224. options.needAlphaBlending = false;
  53225. }
  53226. if (!useVertexColor) {
  53227. options.uniforms.push("color");
  53228. }
  53229. else {
  53230. options.defines.push("#define VERTEXCOLOR");
  53231. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  53232. }
  53233. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  53234. return _this;
  53235. }
  53236. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  53237. /**
  53238. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  53239. * This margin is expressed in world space coordinates, so its value may vary.
  53240. * Default value is 0.1
  53241. * @returns the intersection Threshold value.
  53242. */
  53243. get: function () {
  53244. return this._intersectionThreshold;
  53245. },
  53246. /**
  53247. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  53248. * This margin is expressed in world space coordinates, so its value may vary.
  53249. * @param value the new threshold to apply
  53250. */
  53251. set: function (value) {
  53252. if (this._intersectionThreshold === value) {
  53253. return;
  53254. }
  53255. this._intersectionThreshold = value;
  53256. if (this.geometry) {
  53257. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  53258. }
  53259. },
  53260. enumerable: true,
  53261. configurable: true
  53262. });
  53263. /**
  53264. * Returns the string "LineMesh"
  53265. */
  53266. LinesMesh.prototype.getClassName = function () {
  53267. return "LinesMesh";
  53268. };
  53269. Object.defineProperty(LinesMesh.prototype, "material", {
  53270. get: function () {
  53271. return this._colorShader;
  53272. },
  53273. set: function (value) {
  53274. // Do nothing
  53275. },
  53276. enumerable: true,
  53277. configurable: true
  53278. });
  53279. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  53280. get: function () {
  53281. return false;
  53282. },
  53283. enumerable: true,
  53284. configurable: true
  53285. });
  53286. LinesMesh.prototype.createInstance = function (name) {
  53287. throw new Error("LinesMeshes do not support createInstance.");
  53288. };
  53289. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  53290. if (!this._geometry) {
  53291. return this;
  53292. }
  53293. // VBOs
  53294. this._geometry._bind(this._colorShader.getEffect());
  53295. // Color
  53296. if (!this.useVertexColor) {
  53297. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  53298. }
  53299. return this;
  53300. };
  53301. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  53302. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  53303. return this;
  53304. }
  53305. var engine = this.getScene().getEngine();
  53306. // Draw order
  53307. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  53308. return this;
  53309. };
  53310. LinesMesh.prototype.dispose = function (doNotRecurse) {
  53311. this._colorShader.dispose();
  53312. _super.prototype.dispose.call(this, doNotRecurse);
  53313. };
  53314. /**
  53315. * Returns a new LineMesh object cloned from the current one.
  53316. */
  53317. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  53318. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  53319. };
  53320. return LinesMesh;
  53321. }(BABYLON.Mesh));
  53322. BABYLON.LinesMesh = LinesMesh;
  53323. })(BABYLON || (BABYLON = {}));
  53324. //# sourceMappingURL=babylon.linesMesh.js.map
  53325. var BABYLON;
  53326. (function (BABYLON) {
  53327. var MeshBuilder = /** @class */ (function () {
  53328. function MeshBuilder() {
  53329. }
  53330. MeshBuilder.updateSideOrientation = function (orientation) {
  53331. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  53332. return BABYLON.Mesh.DOUBLESIDE;
  53333. }
  53334. if (orientation === undefined || orientation === null) {
  53335. return BABYLON.Mesh.FRONTSIDE;
  53336. }
  53337. return orientation;
  53338. };
  53339. /**
  53340. * Creates a box mesh.
  53341. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  53342. * The parameter `size` sets the size (float) of each box side (default 1).
  53343. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  53344. * 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).
  53345. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  53346. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53347. * 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).
  53348. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53349. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53350. */
  53351. MeshBuilder.CreateBox = function (name, options, scene) {
  53352. if (scene === void 0) { scene = null; }
  53353. var box = new BABYLON.Mesh(name, scene);
  53354. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53355. box._originalBuilderSideOrientation = options.sideOrientation;
  53356. var vertexData = BABYLON.VertexData.CreateBox(options);
  53357. vertexData.applyToMesh(box, options.updatable);
  53358. return box;
  53359. };
  53360. /**
  53361. * Creates a sphere mesh.
  53362. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  53363. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  53364. * 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`).
  53365. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  53366. * 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
  53367. * 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).
  53368. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53369. * 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).
  53370. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53371. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53372. */
  53373. MeshBuilder.CreateSphere = function (name, options, scene) {
  53374. var sphere = new BABYLON.Mesh(name, scene);
  53375. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53376. sphere._originalBuilderSideOrientation = options.sideOrientation;
  53377. var vertexData = BABYLON.VertexData.CreateSphere(options);
  53378. vertexData.applyToMesh(sphere, options.updatable);
  53379. return sphere;
  53380. };
  53381. /**
  53382. * Creates a plane polygonal mesh. By default, this is a disc.
  53383. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  53384. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  53385. * 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.
  53386. * 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
  53387. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53388. * 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).
  53389. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53390. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53391. */
  53392. MeshBuilder.CreateDisc = function (name, options, scene) {
  53393. if (scene === void 0) { scene = null; }
  53394. var disc = new BABYLON.Mesh(name, scene);
  53395. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53396. disc._originalBuilderSideOrientation = options.sideOrientation;
  53397. var vertexData = BABYLON.VertexData.CreateDisc(options);
  53398. vertexData.applyToMesh(disc, options.updatable);
  53399. return disc;
  53400. };
  53401. /**
  53402. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  53403. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  53404. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  53405. * 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`).
  53406. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  53407. * 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.
  53408. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53409. * 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).
  53410. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53411. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53412. */
  53413. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  53414. var sphere = new BABYLON.Mesh(name, scene);
  53415. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53416. sphere._originalBuilderSideOrientation = options.sideOrientation;
  53417. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  53418. vertexData.applyToMesh(sphere, options.updatable);
  53419. return sphere;
  53420. };
  53421. ;
  53422. /**
  53423. * Creates a ribbon mesh.
  53424. * 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.
  53425. *
  53426. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  53427. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  53428. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  53429. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  53430. * 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.
  53431. * 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.
  53432. * 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
  53433. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53434. * 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).
  53435. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53436. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  53437. * 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.
  53438. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  53439. * 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
  53440. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  53441. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  53442. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53443. */
  53444. MeshBuilder.CreateRibbon = function (name, options, scene) {
  53445. if (scene === void 0) { scene = null; }
  53446. var pathArray = options.pathArray;
  53447. var closeArray = options.closeArray;
  53448. var closePath = options.closePath;
  53449. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53450. var instance = options.instance;
  53451. var updatable = options.updatable;
  53452. if (instance) {
  53453. // positionFunction : ribbon case
  53454. // only pathArray and sideOrientation parameters are taken into account for positions update
  53455. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  53456. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  53457. var positionFunction = function (positions) {
  53458. var minlg = pathArray[0].length;
  53459. var i = 0;
  53460. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  53461. for (var si = 1; si <= ns; si++) {
  53462. for (var p = 0; p < pathArray.length; p++) {
  53463. var path = pathArray[p];
  53464. var l = path.length;
  53465. minlg = (minlg < l) ? minlg : l;
  53466. var j = 0;
  53467. while (j < minlg) {
  53468. positions[i] = path[j].x;
  53469. positions[i + 1] = path[j].y;
  53470. positions[i + 2] = path[j].z;
  53471. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  53472. BABYLON.Tmp.Vector3[0].x = path[j].x;
  53473. }
  53474. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  53475. BABYLON.Tmp.Vector3[1].x = path[j].x;
  53476. }
  53477. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  53478. BABYLON.Tmp.Vector3[0].y = path[j].y;
  53479. }
  53480. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  53481. BABYLON.Tmp.Vector3[1].y = path[j].y;
  53482. }
  53483. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  53484. BABYLON.Tmp.Vector3[0].z = path[j].z;
  53485. }
  53486. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  53487. BABYLON.Tmp.Vector3[1].z = path[j].z;
  53488. }
  53489. j++;
  53490. i += 3;
  53491. }
  53492. if (instance._closePath) {
  53493. positions[i] = path[0].x;
  53494. positions[i + 1] = path[0].y;
  53495. positions[i + 2] = path[0].z;
  53496. i += 3;
  53497. }
  53498. }
  53499. }
  53500. };
  53501. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53502. positionFunction(positions);
  53503. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  53504. instance._boundingInfo.update(instance._worldMatrix);
  53505. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  53506. if (options.colors) {
  53507. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53508. for (var c = 0; c < options.colors.length; c++) {
  53509. colors[c * 4] = options.colors[c].r;
  53510. colors[c * 4 + 1] = options.colors[c].g;
  53511. colors[c * 4 + 2] = options.colors[c].b;
  53512. colors[c * 4 + 3] = options.colors[c].a;
  53513. }
  53514. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  53515. }
  53516. if (options.uvs) {
  53517. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53518. for (var i = 0; i < options.uvs.length; i++) {
  53519. uvs[i * 2] = options.uvs[i].x;
  53520. uvs[i * 2 + 1] = options.uvs[i].y;
  53521. }
  53522. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  53523. }
  53524. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  53525. var indices = instance.getIndices();
  53526. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53527. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  53528. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  53529. if (instance._closePath) {
  53530. var indexFirst = 0;
  53531. var indexLast = 0;
  53532. for (var p = 0; p < pathArray.length; p++) {
  53533. indexFirst = instance._idx[p] * 3;
  53534. if (p + 1 < pathArray.length) {
  53535. indexLast = (instance._idx[p + 1] - 1) * 3;
  53536. }
  53537. else {
  53538. indexLast = normals.length - 3;
  53539. }
  53540. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  53541. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  53542. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  53543. normals[indexLast] = normals[indexFirst];
  53544. normals[indexLast + 1] = normals[indexFirst + 1];
  53545. normals[indexLast + 2] = normals[indexFirst + 2];
  53546. }
  53547. }
  53548. if (!(instance.areNormalsFrozen)) {
  53549. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  53550. }
  53551. }
  53552. return instance;
  53553. }
  53554. else {
  53555. var ribbon = new BABYLON.Mesh(name, scene);
  53556. ribbon._originalBuilderSideOrientation = sideOrientation;
  53557. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  53558. if (closePath) {
  53559. ribbon._idx = vertexData._idx;
  53560. }
  53561. ribbon._closePath = closePath;
  53562. ribbon._closeArray = closeArray;
  53563. vertexData.applyToMesh(ribbon, updatable);
  53564. return ribbon;
  53565. }
  53566. };
  53567. /**
  53568. * Creates a cylinder or a cone mesh.
  53569. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  53570. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  53571. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  53572. * 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.
  53573. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  53574. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  53575. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  53576. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  53577. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  53578. * 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).
  53579. * 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
  53580. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  53581. * 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
  53582. * 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.
  53583. * If `enclose` is false, a ring surface is one element.
  53584. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  53585. * 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
  53586. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53587. * 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).
  53588. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53589. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53590. */
  53591. MeshBuilder.CreateCylinder = function (name, options, scene) {
  53592. var cylinder = new BABYLON.Mesh(name, scene);
  53593. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53594. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  53595. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  53596. vertexData.applyToMesh(cylinder, options.updatable);
  53597. return cylinder;
  53598. };
  53599. /**
  53600. * Creates a torus mesh.
  53601. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  53602. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  53603. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  53604. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  53605. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53606. * 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).
  53607. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53608. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53609. */
  53610. MeshBuilder.CreateTorus = function (name, options, scene) {
  53611. var torus = new BABYLON.Mesh(name, scene);
  53612. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53613. torus._originalBuilderSideOrientation = options.sideOrientation;
  53614. var vertexData = BABYLON.VertexData.CreateTorus(options);
  53615. vertexData.applyToMesh(torus, options.updatable);
  53616. return torus;
  53617. };
  53618. /**
  53619. * Creates a torus knot mesh.
  53620. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  53621. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  53622. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  53623. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  53624. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  53625. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53626. * 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).
  53627. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53628. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53629. */
  53630. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  53631. var torusKnot = new BABYLON.Mesh(name, scene);
  53632. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53633. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  53634. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  53635. vertexData.applyToMesh(torusKnot, options.updatable);
  53636. return torusKnot;
  53637. };
  53638. /**
  53639. * Creates a line system mesh.
  53640. * A line system is a pool of many lines gathered in a single mesh.
  53641. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  53642. * 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.
  53643. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  53644. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  53645. * 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
  53646. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  53647. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  53648. * 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
  53649. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  53650. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53651. */
  53652. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  53653. var instance = options.instance;
  53654. var lines = options.lines;
  53655. var colors = options.colors;
  53656. if (instance) {
  53657. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53658. var vertexColor;
  53659. var lineColors;
  53660. if (colors) {
  53661. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53662. }
  53663. var i = 0;
  53664. var c = 0;
  53665. for (var l = 0; l < lines.length; l++) {
  53666. var points = lines[l];
  53667. for (var p = 0; p < points.length; p++) {
  53668. positions[i] = points[p].x;
  53669. positions[i + 1] = points[p].y;
  53670. positions[i + 2] = points[p].z;
  53671. if (colors && vertexColor) {
  53672. lineColors = colors[l];
  53673. vertexColor[c] = lineColors[p].r;
  53674. vertexColor[c + 1] = lineColors[p].g;
  53675. vertexColor[c + 2] = lineColors[p].b;
  53676. vertexColor[c + 3] = lineColors[p].a;
  53677. c += 4;
  53678. }
  53679. i += 3;
  53680. }
  53681. }
  53682. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  53683. if (colors && vertexColor) {
  53684. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  53685. }
  53686. return instance;
  53687. }
  53688. // line system creation
  53689. var useVertexColor = (colors) ? true : false;
  53690. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  53691. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  53692. vertexData.applyToMesh(lineSystem, options.updatable);
  53693. return lineSystem;
  53694. };
  53695. /**
  53696. * Creates a line mesh.
  53697. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  53698. * 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.
  53699. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  53700. * The parameter `points` is an array successive Vector3.
  53701. * 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
  53702. * The optional parameter `colors` is an array of successive Color4, one per line point.
  53703. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  53704. * When updating an instance, remember that only point positions can change, not the number of points.
  53705. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53706. */
  53707. MeshBuilder.CreateLines = function (name, options, scene) {
  53708. if (scene === void 0) { scene = null; }
  53709. var colors = (options.colors) ? [options.colors] : null;
  53710. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  53711. return lines;
  53712. };
  53713. /**
  53714. * Creates a dashed line mesh.
  53715. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  53716. * 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.
  53717. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  53718. * The parameter `points` is an array successive Vector3.
  53719. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  53720. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  53721. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  53722. * 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
  53723. * When updating an instance, remember that only point positions can change, not the number of points.
  53724. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53725. */
  53726. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  53727. if (scene === void 0) { scene = null; }
  53728. var points = options.points;
  53729. var instance = options.instance;
  53730. var gapSize = options.gapSize || 1;
  53731. var dashSize = options.dashSize || 3;
  53732. if (instance) {
  53733. var positionFunction = function (positions) {
  53734. var curvect = BABYLON.Vector3.Zero();
  53735. var nbSeg = positions.length / 6;
  53736. var lg = 0;
  53737. var nb = 0;
  53738. var shft = 0;
  53739. var dashshft = 0;
  53740. var curshft = 0;
  53741. var p = 0;
  53742. var i = 0;
  53743. var j = 0;
  53744. for (i = 0; i < points.length - 1; i++) {
  53745. points[i + 1].subtractToRef(points[i], curvect);
  53746. lg += curvect.length();
  53747. }
  53748. shft = lg / nbSeg;
  53749. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  53750. for (i = 0; i < points.length - 1; i++) {
  53751. points[i + 1].subtractToRef(points[i], curvect);
  53752. nb = Math.floor(curvect.length() / shft);
  53753. curvect.normalize();
  53754. j = 0;
  53755. while (j < nb && p < positions.length) {
  53756. curshft = shft * j;
  53757. positions[p] = points[i].x + curshft * curvect.x;
  53758. positions[p + 1] = points[i].y + curshft * curvect.y;
  53759. positions[p + 2] = points[i].z + curshft * curvect.z;
  53760. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  53761. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  53762. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  53763. p += 6;
  53764. j++;
  53765. }
  53766. }
  53767. while (p < positions.length) {
  53768. positions[p] = points[i].x;
  53769. positions[p + 1] = points[i].y;
  53770. positions[p + 2] = points[i].z;
  53771. p += 3;
  53772. }
  53773. };
  53774. instance.updateMeshPositions(positionFunction, false);
  53775. return instance;
  53776. }
  53777. // dashed lines creation
  53778. var dashedLines = new BABYLON.LinesMesh(name, scene);
  53779. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  53780. vertexData.applyToMesh(dashedLines, options.updatable);
  53781. dashedLines.dashSize = dashSize;
  53782. dashedLines.gapSize = gapSize;
  53783. return dashedLines;
  53784. };
  53785. /**
  53786. * Creates an extruded shape mesh.
  53787. * 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.
  53788. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  53789. *
  53790. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  53791. * 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
  53792. * extruded along the Z axis.
  53793. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  53794. * 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.
  53795. * The parameter `scale` (float, default 1) is the value to scale the shape.
  53796. * 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
  53797. * 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
  53798. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  53799. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53800. * 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).
  53801. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53802. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  53803. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53804. */
  53805. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  53806. if (scene === void 0) { scene = null; }
  53807. var path = options.path;
  53808. var shape = options.shape;
  53809. var scale = options.scale || 1;
  53810. var rotation = options.rotation || 0;
  53811. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  53812. var updatable = options.updatable;
  53813. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53814. var instance = options.instance || null;
  53815. var invertUV = options.invertUV || false;
  53816. 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);
  53817. };
  53818. /**
  53819. * Creates an custom extruded shape mesh.
  53820. * 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.
  53821. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  53822. *
  53823. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  53824. * 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
  53825. * extruded along the Z axis.
  53826. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  53827. * 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
  53828. * and the distance of this point from the begining of the path :
  53829. * ```javascript
  53830. * var rotationFunction = function(i, distance) {
  53831. * // do things
  53832. * return rotationValue; }
  53833. * ```
  53834. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  53835. * 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
  53836. * and the distance of this point from the begining of the path :
  53837. * ```javascript
  53838. * var scaleFunction = function(i, distance) {
  53839. * // do things
  53840. * return scaleValue;}
  53841. * ```
  53842. * It must returns a float value that will be the scale value applied to the shape on each path point.
  53843. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  53844. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  53845. * 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
  53846. * 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
  53847. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  53848. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53849. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  53850. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53851. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  53852. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53853. */
  53854. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  53855. var path = options.path;
  53856. var shape = options.shape;
  53857. var scaleFunction = options.scaleFunction || (function () { return 1; });
  53858. var rotationFunction = options.rotationFunction || (function () { return 0; });
  53859. var ribbonCloseArray = options.ribbonCloseArray || false;
  53860. var ribbonClosePath = options.ribbonClosePath || false;
  53861. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  53862. var updatable = options.updatable;
  53863. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53864. var instance = options.instance;
  53865. var invertUV = options.invertUV || false;
  53866. 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);
  53867. };
  53868. /**
  53869. * Creates lathe mesh.
  53870. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  53871. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  53872. *
  53873. * 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
  53874. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  53875. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  53876. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  53877. * 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.
  53878. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  53879. * 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
  53880. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53881. * 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).
  53882. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53883. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  53884. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53885. */
  53886. MeshBuilder.CreateLathe = function (name, options, scene) {
  53887. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  53888. var closed = (options.closed === undefined) ? true : options.closed;
  53889. var shape = options.shape;
  53890. var radius = options.radius || 1;
  53891. var tessellation = options.tessellation || 64;
  53892. var updatable = options.updatable;
  53893. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53894. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  53895. var pi2 = Math.PI * 2;
  53896. var paths = new Array();
  53897. var invertUV = options.invertUV || false;
  53898. var i = 0;
  53899. var p = 0;
  53900. var step = pi2 / tessellation * arc;
  53901. var rotated;
  53902. var path = new Array();
  53903. ;
  53904. for (i = 0; i <= tessellation; i++) {
  53905. var path = [];
  53906. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  53907. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  53908. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  53909. }
  53910. for (p = 0; p < shape.length; p++) {
  53911. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  53912. path.push(rotated);
  53913. }
  53914. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  53915. 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));
  53916. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  53917. }
  53918. paths.push(path);
  53919. }
  53920. // lathe ribbon
  53921. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  53922. return lathe;
  53923. };
  53924. /**
  53925. * Creates a plane mesh.
  53926. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  53927. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  53928. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  53929. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  53930. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53931. * 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).
  53932. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53933. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53934. */
  53935. MeshBuilder.CreatePlane = function (name, options, scene) {
  53936. var plane = new BABYLON.Mesh(name, scene);
  53937. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53938. plane._originalBuilderSideOrientation = options.sideOrientation;
  53939. var vertexData = BABYLON.VertexData.CreatePlane(options);
  53940. vertexData.applyToMesh(plane, options.updatable);
  53941. if (options.sourcePlane) {
  53942. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  53943. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  53944. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  53945. plane.rotate(vectorProduct, product);
  53946. }
  53947. return plane;
  53948. };
  53949. /**
  53950. * Creates a ground mesh.
  53951. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  53952. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  53953. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  53954. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53955. */
  53956. MeshBuilder.CreateGround = function (name, options, scene) {
  53957. var ground = new BABYLON.GroundMesh(name, scene);
  53958. ground._setReady(false);
  53959. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  53960. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  53961. ground._width = options.width || 1;
  53962. ground._height = options.height || 1;
  53963. ground._maxX = ground._width / 2;
  53964. ground._maxZ = ground._height / 2;
  53965. ground._minX = -ground._maxX;
  53966. ground._minZ = -ground._maxZ;
  53967. var vertexData = BABYLON.VertexData.CreateGround(options);
  53968. vertexData.applyToMesh(ground, options.updatable);
  53969. ground._setReady(true);
  53970. return ground;
  53971. };
  53972. /**
  53973. * Creates a tiled ground mesh.
  53974. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  53975. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  53976. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  53977. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  53978. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  53979. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  53980. * numbers of subdivisions on the ground width and height of each tile.
  53981. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53982. */
  53983. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  53984. var tiledGround = new BABYLON.Mesh(name, scene);
  53985. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  53986. vertexData.applyToMesh(tiledGround, options.updatable);
  53987. return tiledGround;
  53988. };
  53989. /**
  53990. * Creates a ground mesh from a height map.
  53991. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  53992. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  53993. * The parameter `url` sets the URL of the height map image resource.
  53994. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  53995. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  53996. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  53997. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  53998. * 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.
  53999. * 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).
  54000. * This function is passed the newly built mesh :
  54001. * ```javascript
  54002. * function(mesh) { // do things
  54003. * return; }
  54004. * ```
  54005. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54006. */
  54007. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  54008. var width = options.width || 10.0;
  54009. var height = options.height || 10.0;
  54010. var subdivisions = options.subdivisions || 1 | 0;
  54011. var minHeight = options.minHeight || 0.0;
  54012. var maxHeight = options.maxHeight || 1.0;
  54013. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  54014. var updatable = options.updatable;
  54015. var onReady = options.onReady;
  54016. var ground = new BABYLON.GroundMesh(name, scene);
  54017. ground._subdivisionsX = subdivisions;
  54018. ground._subdivisionsY = subdivisions;
  54019. ground._width = width;
  54020. ground._height = height;
  54021. ground._maxX = ground._width / 2.0;
  54022. ground._maxZ = ground._height / 2.0;
  54023. ground._minX = -ground._maxX;
  54024. ground._minZ = -ground._maxZ;
  54025. ground._setReady(false);
  54026. var onload = function (img) {
  54027. // Getting height map data
  54028. var canvas = document.createElement("canvas");
  54029. var context = canvas.getContext("2d");
  54030. if (!context) {
  54031. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  54032. }
  54033. if (scene.isDisposed) {
  54034. return;
  54035. }
  54036. var bufferWidth = img.width;
  54037. var bufferHeight = img.height;
  54038. canvas.width = bufferWidth;
  54039. canvas.height = bufferHeight;
  54040. context.drawImage(img, 0, 0);
  54041. // Create VertexData from map data
  54042. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  54043. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  54044. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  54045. width: width, height: height,
  54046. subdivisions: subdivisions,
  54047. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  54048. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  54049. });
  54050. vertexData.applyToMesh(ground, updatable);
  54051. ground._setReady(true);
  54052. //execute ready callback, if set
  54053. if (onReady) {
  54054. onReady(ground);
  54055. }
  54056. };
  54057. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  54058. return ground;
  54059. };
  54060. /**
  54061. * Creates a polygon mesh.
  54062. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  54063. * 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.
  54064. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54065. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54066. * 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).
  54067. * Remember you can only change the shape positions, not their number when updating a polygon.
  54068. */
  54069. MeshBuilder.CreatePolygon = function (name, options, scene) {
  54070. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54071. var shape = options.shape;
  54072. var holes = options.holes || [];
  54073. var depth = options.depth || 0;
  54074. var contours = [];
  54075. var hole = [];
  54076. for (var i = 0; i < shape.length; i++) {
  54077. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  54078. }
  54079. var epsilon = 0.00000001;
  54080. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  54081. contours.pop();
  54082. }
  54083. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  54084. for (var hNb = 0; hNb < holes.length; hNb++) {
  54085. hole = [];
  54086. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  54087. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  54088. }
  54089. polygonTriangulation.addHole(hole);
  54090. }
  54091. var polygon = polygonTriangulation.build(options.updatable, depth);
  54092. polygon._originalBuilderSideOrientation = options.sideOrientation;
  54093. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  54094. vertexData.applyToMesh(polygon, options.updatable);
  54095. return polygon;
  54096. };
  54097. ;
  54098. /**
  54099. * Creates an extruded polygon mesh, with depth in the Y direction.
  54100. * 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).
  54101. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  54102. */
  54103. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  54104. return MeshBuilder.CreatePolygon(name, options, scene);
  54105. };
  54106. ;
  54107. /**
  54108. * Creates a tube mesh.
  54109. * 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.
  54110. *
  54111. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  54112. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  54113. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  54114. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  54115. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  54116. * 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.
  54117. * It must return a radius value (positive float) :
  54118. * ```javascript
  54119. * var radiusFunction = function(i, distance) {
  54120. * // do things
  54121. * return radius; }
  54122. * ```
  54123. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  54124. * 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
  54125. * 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
  54126. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54127. * 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).
  54128. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54129. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54130. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54131. */
  54132. MeshBuilder.CreateTube = function (name, options, scene) {
  54133. var path = options.path;
  54134. var instance = options.instance;
  54135. var radius = 1.0;
  54136. if (instance) {
  54137. radius = instance.radius;
  54138. }
  54139. if (options.radius !== undefined) {
  54140. radius = options.radius;
  54141. }
  54142. ;
  54143. var tessellation = options.tessellation || 64 | 0;
  54144. var radiusFunction = options.radiusFunction || null;
  54145. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  54146. var invertUV = options.invertUV || false;
  54147. var updatable = options.updatable;
  54148. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54149. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  54150. // tube geometry
  54151. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  54152. var tangents = path3D.getTangents();
  54153. var normals = path3D.getNormals();
  54154. var distances = path3D.getDistances();
  54155. var pi2 = Math.PI * 2;
  54156. var step = pi2 / tessellation * arc;
  54157. var returnRadius = function () { return radius; };
  54158. var radiusFunctionFinal = radiusFunction || returnRadius;
  54159. var circlePath;
  54160. var rad;
  54161. var normal;
  54162. var rotated;
  54163. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  54164. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  54165. for (var i = 0; i < path.length; i++) {
  54166. rad = radiusFunctionFinal(i, distances[i]); // current radius
  54167. circlePath = Array(); // current circle array
  54168. normal = normals[i]; // current normal
  54169. for (var t = 0; t < tessellation; t++) {
  54170. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  54171. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  54172. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  54173. rotated.scaleInPlace(rad).addInPlace(path[i]);
  54174. circlePath[t] = rotated;
  54175. }
  54176. circlePaths[index] = circlePath;
  54177. index++;
  54178. }
  54179. // cap
  54180. var capPath = function (nbPoints, pathIndex) {
  54181. var pointCap = Array();
  54182. for (var i = 0; i < nbPoints; i++) {
  54183. pointCap.push(path[pathIndex]);
  54184. }
  54185. return pointCap;
  54186. };
  54187. switch (cap) {
  54188. case BABYLON.Mesh.NO_CAP:
  54189. break;
  54190. case BABYLON.Mesh.CAP_START:
  54191. circlePaths[0] = capPath(tessellation, 0);
  54192. circlePaths[1] = circlePaths[2].slice(0);
  54193. break;
  54194. case BABYLON.Mesh.CAP_END:
  54195. circlePaths[index] = circlePaths[index - 1].slice(0);
  54196. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  54197. break;
  54198. case BABYLON.Mesh.CAP_ALL:
  54199. circlePaths[0] = capPath(tessellation, 0);
  54200. circlePaths[1] = circlePaths[2].slice(0);
  54201. circlePaths[index] = circlePaths[index - 1].slice(0);
  54202. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  54203. break;
  54204. default:
  54205. break;
  54206. }
  54207. return circlePaths;
  54208. };
  54209. var path3D;
  54210. var pathArray;
  54211. if (instance) {
  54212. var arc = options.arc || instance.arc;
  54213. path3D = (instance.path3D).update(path);
  54214. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  54215. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  54216. instance.path3D = path3D;
  54217. instance.pathArray = pathArray;
  54218. instance.arc = arc;
  54219. instance.radius = radius;
  54220. return instance;
  54221. }
  54222. // tube creation
  54223. path3D = new BABYLON.Path3D(path);
  54224. var newPathArray = new Array();
  54225. cap = (cap < 0 || cap > 3) ? 0 : cap;
  54226. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  54227. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  54228. tube.pathArray = pathArray;
  54229. tube.path3D = path3D;
  54230. tube.tessellation = tessellation;
  54231. tube.cap = cap;
  54232. tube.arc = options.arc;
  54233. tube.radius = radius;
  54234. return tube;
  54235. };
  54236. /**
  54237. * Creates a polyhedron mesh.
  54238. *
  54239. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  54240. * 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
  54241. * to choose the wanted type.
  54242. * The parameter `size` (positive float, default 1) sets the polygon size.
  54243. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  54244. * 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`.
  54245. * 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
  54246. * 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)`).
  54247. * 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
  54248. * 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.
  54249. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54250. * 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).
  54251. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54252. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54253. */
  54254. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  54255. var polyhedron = new BABYLON.Mesh(name, scene);
  54256. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54257. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  54258. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  54259. vertexData.applyToMesh(polyhedron, options.updatable);
  54260. return polyhedron;
  54261. };
  54262. /**
  54263. * Creates a decal mesh.
  54264. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  54265. * 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.
  54266. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  54267. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  54268. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  54269. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  54270. */
  54271. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  54272. var indices = sourceMesh.getIndices();
  54273. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54274. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54275. var position = options.position || BABYLON.Vector3.Zero();
  54276. var normal = options.normal || BABYLON.Vector3.Up();
  54277. var size = options.size || BABYLON.Vector3.One();
  54278. var angle = options.angle || 0;
  54279. // Getting correct rotation
  54280. if (!normal) {
  54281. var target = new BABYLON.Vector3(0, 0, 1);
  54282. var camera = sourceMesh.getScene().activeCamera;
  54283. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  54284. normal = camera.globalPosition.subtract(cameraWorldTarget);
  54285. }
  54286. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  54287. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  54288. var pitch = Math.atan2(normal.y, len);
  54289. // Matrix
  54290. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  54291. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  54292. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  54293. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  54294. var vertexData = new BABYLON.VertexData();
  54295. vertexData.indices = [];
  54296. vertexData.positions = [];
  54297. vertexData.normals = [];
  54298. vertexData.uvs = [];
  54299. var currentVertexDataIndex = 0;
  54300. var extractDecalVector3 = function (indexId) {
  54301. var result = new BABYLON.PositionNormalVertex();
  54302. if (!indices || !positions || !normals) {
  54303. return result;
  54304. }
  54305. var vertexId = indices[indexId];
  54306. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  54307. // Send vector to decal local world
  54308. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  54309. // Get normal
  54310. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  54311. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  54312. return result;
  54313. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  54314. var clip = function (vertices, axis) {
  54315. if (vertices.length === 0) {
  54316. return vertices;
  54317. }
  54318. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  54319. var clipVertices = function (v0, v1) {
  54320. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  54321. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  54322. };
  54323. var result = new Array();
  54324. for (var index = 0; index < vertices.length; index += 3) {
  54325. var v1Out;
  54326. var v2Out;
  54327. var v3Out;
  54328. var total = 0;
  54329. var nV1 = null;
  54330. var nV2 = null;
  54331. var nV3 = null;
  54332. var nV4 = null;
  54333. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  54334. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  54335. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  54336. v1Out = d1 > 0;
  54337. v2Out = d2 > 0;
  54338. v3Out = d3 > 0;
  54339. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  54340. switch (total) {
  54341. case 0:
  54342. result.push(vertices[index]);
  54343. result.push(vertices[index + 1]);
  54344. result.push(vertices[index + 2]);
  54345. break;
  54346. case 1:
  54347. if (v1Out) {
  54348. nV1 = vertices[index + 1];
  54349. nV2 = vertices[index + 2];
  54350. nV3 = clipVertices(vertices[index], nV1);
  54351. nV4 = clipVertices(vertices[index], nV2);
  54352. }
  54353. if (v2Out) {
  54354. nV1 = vertices[index];
  54355. nV2 = vertices[index + 2];
  54356. nV3 = clipVertices(vertices[index + 1], nV1);
  54357. nV4 = clipVertices(vertices[index + 1], nV2);
  54358. result.push(nV3);
  54359. result.push(nV2.clone());
  54360. result.push(nV1.clone());
  54361. result.push(nV2.clone());
  54362. result.push(nV3.clone());
  54363. result.push(nV4);
  54364. break;
  54365. }
  54366. if (v3Out) {
  54367. nV1 = vertices[index];
  54368. nV2 = vertices[index + 1];
  54369. nV3 = clipVertices(vertices[index + 2], nV1);
  54370. nV4 = clipVertices(vertices[index + 2], nV2);
  54371. }
  54372. if (nV1 && nV2 && nV3 && nV4) {
  54373. result.push(nV1.clone());
  54374. result.push(nV2.clone());
  54375. result.push(nV3);
  54376. result.push(nV4);
  54377. result.push(nV3.clone());
  54378. result.push(nV2.clone());
  54379. }
  54380. break;
  54381. case 2:
  54382. if (!v1Out) {
  54383. nV1 = vertices[index].clone();
  54384. nV2 = clipVertices(nV1, vertices[index + 1]);
  54385. nV3 = clipVertices(nV1, vertices[index + 2]);
  54386. result.push(nV1);
  54387. result.push(nV2);
  54388. result.push(nV3);
  54389. }
  54390. if (!v2Out) {
  54391. nV1 = vertices[index + 1].clone();
  54392. nV2 = clipVertices(nV1, vertices[index + 2]);
  54393. nV3 = clipVertices(nV1, vertices[index]);
  54394. result.push(nV1);
  54395. result.push(nV2);
  54396. result.push(nV3);
  54397. }
  54398. if (!v3Out) {
  54399. nV1 = vertices[index + 2].clone();
  54400. nV2 = clipVertices(nV1, vertices[index]);
  54401. nV3 = clipVertices(nV1, vertices[index + 1]);
  54402. result.push(nV1);
  54403. result.push(nV2);
  54404. result.push(nV3);
  54405. }
  54406. break;
  54407. case 3:
  54408. break;
  54409. }
  54410. }
  54411. return result;
  54412. };
  54413. for (var index = 0; index < indices.length; index += 3) {
  54414. var faceVertices = new Array();
  54415. faceVertices.push(extractDecalVector3(index));
  54416. faceVertices.push(extractDecalVector3(index + 1));
  54417. faceVertices.push(extractDecalVector3(index + 2));
  54418. // Clip
  54419. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  54420. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  54421. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  54422. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  54423. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  54424. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  54425. if (faceVertices.length === 0) {
  54426. continue;
  54427. }
  54428. // Add UVs and get back to world
  54429. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  54430. var vertex = faceVertices[vIndex];
  54431. //TODO check for Int32Array | Uint32Array | Uint16Array
  54432. vertexData.indices.push(currentVertexDataIndex);
  54433. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  54434. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  54435. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  54436. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  54437. currentVertexDataIndex++;
  54438. }
  54439. }
  54440. // Return mesh
  54441. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  54442. vertexData.applyToMesh(decal);
  54443. decal.position = position.clone();
  54444. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  54445. return decal;
  54446. };
  54447. // Privates
  54448. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  54449. // extrusion geometry
  54450. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  54451. var tangents = path3D.getTangents();
  54452. var normals = path3D.getNormals();
  54453. var binormals = path3D.getBinormals();
  54454. var distances = path3D.getDistances();
  54455. var angle = 0;
  54456. var returnScale = function () { return scale !== null ? scale : 1; };
  54457. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  54458. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  54459. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  54460. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  54461. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  54462. for (var i = 0; i < curve.length; i++) {
  54463. var shapePath = new Array();
  54464. var angleStep = rotate(i, distances[i]);
  54465. var scaleRatio = scl(i, distances[i]);
  54466. for (var p = 0; p < shape.length; p++) {
  54467. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  54468. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  54469. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  54470. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  54471. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  54472. shapePath[p] = rotated;
  54473. }
  54474. shapePaths[index] = shapePath;
  54475. angle += angleStep;
  54476. index++;
  54477. }
  54478. // cap
  54479. var capPath = function (shapePath) {
  54480. var pointCap = Array();
  54481. var barycenter = BABYLON.Vector3.Zero();
  54482. var i;
  54483. for (i = 0; i < shapePath.length; i++) {
  54484. barycenter.addInPlace(shapePath[i]);
  54485. }
  54486. barycenter.scaleInPlace(1.0 / shapePath.length);
  54487. for (i = 0; i < shapePath.length; i++) {
  54488. pointCap.push(barycenter);
  54489. }
  54490. return pointCap;
  54491. };
  54492. switch (cap) {
  54493. case BABYLON.Mesh.NO_CAP:
  54494. break;
  54495. case BABYLON.Mesh.CAP_START:
  54496. shapePaths[0] = capPath(shapePaths[2]);
  54497. shapePaths[1] = shapePaths[2];
  54498. break;
  54499. case BABYLON.Mesh.CAP_END:
  54500. shapePaths[index] = shapePaths[index - 1];
  54501. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  54502. break;
  54503. case BABYLON.Mesh.CAP_ALL:
  54504. shapePaths[0] = capPath(shapePaths[2]);
  54505. shapePaths[1] = shapePaths[2];
  54506. shapePaths[index] = shapePaths[index - 1];
  54507. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  54508. break;
  54509. default:
  54510. break;
  54511. }
  54512. return shapePaths;
  54513. };
  54514. var path3D;
  54515. var pathArray;
  54516. if (instance) {
  54517. path3D = (instance.path3D).update(curve);
  54518. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  54519. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  54520. return instance;
  54521. }
  54522. // extruded shape creation
  54523. path3D = new BABYLON.Path3D(curve);
  54524. var newShapePaths = new Array();
  54525. cap = (cap < 0 || cap > 3) ? 0 : cap;
  54526. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  54527. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  54528. extrudedGeneric.pathArray = pathArray;
  54529. extrudedGeneric.path3D = path3D;
  54530. extrudedGeneric.cap = cap;
  54531. return extrudedGeneric;
  54532. };
  54533. return MeshBuilder;
  54534. }());
  54535. BABYLON.MeshBuilder = MeshBuilder;
  54536. })(BABYLON || (BABYLON = {}));
  54537. //# sourceMappingURL=babylon.meshBuilder.js.map
  54538. var BABYLON;
  54539. (function (BABYLON) {
  54540. var AudioEngine = /** @class */ (function () {
  54541. function AudioEngine() {
  54542. this._audioContext = null;
  54543. this._audioContextInitialized = false;
  54544. this.canUseWebAudio = false;
  54545. this.WarnedWebAudioUnsupported = false;
  54546. this.unlocked = false;
  54547. this.isMP3supported = false;
  54548. this.isOGGsupported = false;
  54549. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  54550. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  54551. this.canUseWebAudio = true;
  54552. }
  54553. var audioElem = document.createElement('audio');
  54554. try {
  54555. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  54556. this.isMP3supported = true;
  54557. }
  54558. }
  54559. catch (e) {
  54560. // protect error during capability check.
  54561. }
  54562. try {
  54563. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  54564. this.isOGGsupported = true;
  54565. }
  54566. }
  54567. catch (e) {
  54568. // protect error during capability check.
  54569. }
  54570. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  54571. this._unlockiOSaudio();
  54572. }
  54573. else {
  54574. this.unlocked = true;
  54575. }
  54576. }
  54577. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  54578. get: function () {
  54579. if (!this._audioContextInitialized) {
  54580. this._initializeAudioContext();
  54581. }
  54582. return this._audioContext;
  54583. },
  54584. enumerable: true,
  54585. configurable: true
  54586. });
  54587. AudioEngine.prototype._unlockiOSaudio = function () {
  54588. var _this = this;
  54589. var unlockaudio = function () {
  54590. if (!_this.audioContext) {
  54591. return;
  54592. }
  54593. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  54594. var source = _this.audioContext.createBufferSource();
  54595. source.buffer = buffer;
  54596. source.connect(_this.audioContext.destination);
  54597. source.start(0);
  54598. setTimeout(function () {
  54599. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  54600. _this.unlocked = true;
  54601. window.removeEventListener('touchend', unlockaudio, false);
  54602. if (_this.onAudioUnlocked) {
  54603. _this.onAudioUnlocked();
  54604. }
  54605. }
  54606. }, 0);
  54607. };
  54608. window.addEventListener('touchend', unlockaudio, false);
  54609. };
  54610. AudioEngine.prototype._initializeAudioContext = function () {
  54611. try {
  54612. if (this.canUseWebAudio) {
  54613. this._audioContext = new AudioContext();
  54614. // create a global volume gain node
  54615. this.masterGain = this._audioContext.createGain();
  54616. this.masterGain.gain.value = 1;
  54617. this.masterGain.connect(this._audioContext.destination);
  54618. this._audioContextInitialized = true;
  54619. }
  54620. }
  54621. catch (e) {
  54622. this.canUseWebAudio = false;
  54623. BABYLON.Tools.Error("Web Audio: " + e.message);
  54624. }
  54625. };
  54626. AudioEngine.prototype.dispose = function () {
  54627. if (this.canUseWebAudio && this._audioContextInitialized) {
  54628. if (this._connectedAnalyser && this._audioContext) {
  54629. this._connectedAnalyser.stopDebugCanvas();
  54630. this._connectedAnalyser.dispose();
  54631. this.masterGain.disconnect();
  54632. this.masterGain.connect(this._audioContext.destination);
  54633. this._connectedAnalyser = null;
  54634. }
  54635. this.masterGain.gain.value = 1;
  54636. }
  54637. this.WarnedWebAudioUnsupported = false;
  54638. };
  54639. AudioEngine.prototype.getGlobalVolume = function () {
  54640. if (this.canUseWebAudio && this._audioContextInitialized) {
  54641. return this.masterGain.gain.value;
  54642. }
  54643. else {
  54644. return -1;
  54645. }
  54646. };
  54647. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  54648. if (this.canUseWebAudio && this._audioContextInitialized) {
  54649. this.masterGain.gain.value = newVolume;
  54650. }
  54651. };
  54652. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  54653. if (this._connectedAnalyser) {
  54654. this._connectedAnalyser.stopDebugCanvas();
  54655. }
  54656. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  54657. this._connectedAnalyser = analyser;
  54658. this.masterGain.disconnect();
  54659. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  54660. }
  54661. };
  54662. return AudioEngine;
  54663. }());
  54664. BABYLON.AudioEngine = AudioEngine;
  54665. })(BABYLON || (BABYLON = {}));
  54666. //# sourceMappingURL=babylon.audioEngine.js.map
  54667. var BABYLON;
  54668. (function (BABYLON) {
  54669. var Sound = /** @class */ (function () {
  54670. /**
  54671. * Create a sound and attach it to a scene
  54672. * @param name Name of your sound
  54673. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  54674. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  54675. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  54676. */
  54677. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  54678. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  54679. var _this = this;
  54680. this.autoplay = false;
  54681. this.loop = false;
  54682. this.useCustomAttenuation = false;
  54683. this.spatialSound = false;
  54684. this.refDistance = 1;
  54685. this.rolloffFactor = 1;
  54686. this.maxDistance = 100;
  54687. this.distanceModel = "linear";
  54688. this._panningModel = "equalpower";
  54689. this._playbackRate = 1;
  54690. this._streaming = false;
  54691. this._startTime = 0;
  54692. this._startOffset = 0;
  54693. this._position = BABYLON.Vector3.Zero();
  54694. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  54695. this._volume = 1;
  54696. this._isReadyToPlay = false;
  54697. this.isPlaying = false;
  54698. this.isPaused = false;
  54699. this._isDirectional = false;
  54700. // Used if you'd like to create a directional sound.
  54701. // If not set, the sound will be omnidirectional
  54702. this._coneInnerAngle = 360;
  54703. this._coneOuterAngle = 360;
  54704. this._coneOuterGain = 0;
  54705. this._isOutputConnected = false;
  54706. this._urlType = "Unknown";
  54707. this.name = name;
  54708. this._scene = scene;
  54709. this._readyToPlayCallback = readyToPlayCallback;
  54710. // Default custom attenuation function is a linear attenuation
  54711. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  54712. if (currentDistance < maxDistance) {
  54713. return currentVolume * (1 - currentDistance / maxDistance);
  54714. }
  54715. else {
  54716. return 0;
  54717. }
  54718. };
  54719. if (options) {
  54720. this.autoplay = options.autoplay || false;
  54721. this.loop = options.loop || false;
  54722. // if volume === 0, we need another way to check this option
  54723. if (options.volume !== undefined) {
  54724. this._volume = options.volume;
  54725. }
  54726. this.spatialSound = options.spatialSound || false;
  54727. this.maxDistance = options.maxDistance || 100;
  54728. this.useCustomAttenuation = options.useCustomAttenuation || false;
  54729. this.rolloffFactor = options.rolloffFactor || 1;
  54730. this.refDistance = options.refDistance || 1;
  54731. this.distanceModel = options.distanceModel || "linear";
  54732. this._playbackRate = options.playbackRate || 1;
  54733. this._streaming = options.streaming || false;
  54734. }
  54735. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  54736. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  54737. this._soundGain.gain.value = this._volume;
  54738. this._inputAudioNode = this._soundGain;
  54739. this._ouputAudioNode = this._soundGain;
  54740. if (this.spatialSound) {
  54741. this._createSpatialParameters();
  54742. }
  54743. this._scene.mainSoundTrack.AddSound(this);
  54744. var validParameter = true;
  54745. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  54746. if (urlOrArrayBuffer) {
  54747. if (typeof (urlOrArrayBuffer) === "string")
  54748. this._urlType = "String";
  54749. if (Array.isArray(urlOrArrayBuffer))
  54750. this._urlType = "Array";
  54751. if (urlOrArrayBuffer instanceof ArrayBuffer)
  54752. this._urlType = "ArrayBuffer";
  54753. var urls = [];
  54754. var codecSupportedFound = false;
  54755. switch (this._urlType) {
  54756. case "ArrayBuffer":
  54757. if (urlOrArrayBuffer.byteLength > 0) {
  54758. codecSupportedFound = true;
  54759. this._soundLoaded(urlOrArrayBuffer);
  54760. }
  54761. break;
  54762. case "String":
  54763. urls.push(urlOrArrayBuffer);
  54764. case "Array":
  54765. if (urls.length === 0)
  54766. urls = urlOrArrayBuffer;
  54767. // If we found a supported format, we load it immediately and stop the loop
  54768. for (var i = 0; i < urls.length; i++) {
  54769. var url = urls[i];
  54770. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  54771. codecSupportedFound = true;
  54772. }
  54773. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  54774. codecSupportedFound = true;
  54775. }
  54776. if (url.indexOf(".wav", url.length - 4) !== -1) {
  54777. codecSupportedFound = true;
  54778. }
  54779. if (url.indexOf("blob:") !== -1) {
  54780. codecSupportedFound = true;
  54781. }
  54782. if (codecSupportedFound) {
  54783. // Loading sound using XHR2
  54784. if (!this._streaming) {
  54785. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  54786. }
  54787. else {
  54788. this._htmlAudioElement = new Audio(url);
  54789. this._htmlAudioElement.controls = false;
  54790. this._htmlAudioElement.loop = this.loop;
  54791. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  54792. this._htmlAudioElement.preload = "auto";
  54793. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  54794. _this._isReadyToPlay = true;
  54795. if (_this.autoplay) {
  54796. _this.play();
  54797. }
  54798. if (_this._readyToPlayCallback) {
  54799. _this._readyToPlayCallback();
  54800. }
  54801. });
  54802. document.body.appendChild(this._htmlAudioElement);
  54803. }
  54804. break;
  54805. }
  54806. }
  54807. break;
  54808. default:
  54809. validParameter = false;
  54810. break;
  54811. }
  54812. if (!validParameter) {
  54813. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  54814. }
  54815. else {
  54816. if (!codecSupportedFound) {
  54817. this._isReadyToPlay = true;
  54818. // Simulating a ready to play event to avoid breaking code path
  54819. if (this._readyToPlayCallback) {
  54820. window.setTimeout(function () {
  54821. if (_this._readyToPlayCallback) {
  54822. _this._readyToPlayCallback();
  54823. }
  54824. }, 1000);
  54825. }
  54826. }
  54827. }
  54828. }
  54829. }
  54830. else {
  54831. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  54832. this._scene.mainSoundTrack.AddSound(this);
  54833. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  54834. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  54835. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  54836. }
  54837. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  54838. if (this._readyToPlayCallback) {
  54839. window.setTimeout(function () {
  54840. if (_this._readyToPlayCallback) {
  54841. _this._readyToPlayCallback();
  54842. }
  54843. }, 1000);
  54844. }
  54845. }
  54846. }
  54847. Sound.prototype.dispose = function () {
  54848. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  54849. if (this.isPlaying) {
  54850. this.stop();
  54851. }
  54852. this._isReadyToPlay = false;
  54853. if (this.soundTrackId === -1) {
  54854. this._scene.mainSoundTrack.RemoveSound(this);
  54855. }
  54856. else {
  54857. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  54858. }
  54859. if (this._soundGain) {
  54860. this._soundGain.disconnect();
  54861. this._soundGain = null;
  54862. }
  54863. if (this._soundPanner) {
  54864. this._soundPanner.disconnect();
  54865. this._soundPanner = null;
  54866. }
  54867. if (this._soundSource) {
  54868. this._soundSource.disconnect();
  54869. this._soundSource = null;
  54870. }
  54871. this._audioBuffer = null;
  54872. if (this._htmlAudioElement) {
  54873. this._htmlAudioElement.pause();
  54874. this._htmlAudioElement.src = "";
  54875. document.body.removeChild(this._htmlAudioElement);
  54876. }
  54877. if (this._connectedMesh && this._registerFunc) {
  54878. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  54879. this._connectedMesh = null;
  54880. }
  54881. }
  54882. };
  54883. Sound.prototype.isReady = function () {
  54884. return this._isReadyToPlay;
  54885. };
  54886. Sound.prototype._soundLoaded = function (audioData) {
  54887. var _this = this;
  54888. if (!BABYLON.Engine.audioEngine.audioContext) {
  54889. return;
  54890. }
  54891. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  54892. _this._audioBuffer = buffer;
  54893. _this._isReadyToPlay = true;
  54894. if (_this.autoplay) {
  54895. _this.play();
  54896. }
  54897. if (_this._readyToPlayCallback) {
  54898. _this._readyToPlayCallback();
  54899. }
  54900. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  54901. };
  54902. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  54903. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  54904. this._audioBuffer = audioBuffer;
  54905. this._isReadyToPlay = true;
  54906. }
  54907. };
  54908. Sound.prototype.updateOptions = function (options) {
  54909. if (options) {
  54910. this.loop = options.loop || this.loop;
  54911. this.maxDistance = options.maxDistance || this.maxDistance;
  54912. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  54913. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  54914. this.refDistance = options.refDistance || this.refDistance;
  54915. this.distanceModel = options.distanceModel || this.distanceModel;
  54916. this._playbackRate = options.playbackRate || this._playbackRate;
  54917. this._updateSpatialParameters();
  54918. if (this.isPlaying) {
  54919. if (this._streaming) {
  54920. this._htmlAudioElement.playbackRate = this._playbackRate;
  54921. }
  54922. else {
  54923. if (this._soundSource) {
  54924. this._soundSource.playbackRate.value = this._playbackRate;
  54925. }
  54926. }
  54927. }
  54928. }
  54929. };
  54930. Sound.prototype._createSpatialParameters = function () {
  54931. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  54932. if (this._scene.headphone) {
  54933. this._panningModel = "HRTF";
  54934. }
  54935. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  54936. this._updateSpatialParameters();
  54937. this._soundPanner.connect(this._ouputAudioNode);
  54938. this._inputAudioNode = this._soundPanner;
  54939. }
  54940. };
  54941. Sound.prototype._updateSpatialParameters = function () {
  54942. if (this.spatialSound && this._soundPanner) {
  54943. if (this.useCustomAttenuation) {
  54944. // Tricks to disable in a way embedded Web Audio attenuation
  54945. this._soundPanner.distanceModel = "linear";
  54946. this._soundPanner.maxDistance = Number.MAX_VALUE;
  54947. this._soundPanner.refDistance = 1;
  54948. this._soundPanner.rolloffFactor = 1;
  54949. this._soundPanner.panningModel = this._panningModel;
  54950. }
  54951. else {
  54952. this._soundPanner.distanceModel = this.distanceModel;
  54953. this._soundPanner.maxDistance = this.maxDistance;
  54954. this._soundPanner.refDistance = this.refDistance;
  54955. this._soundPanner.rolloffFactor = this.rolloffFactor;
  54956. this._soundPanner.panningModel = this._panningModel;
  54957. }
  54958. }
  54959. };
  54960. Sound.prototype.switchPanningModelToHRTF = function () {
  54961. this._panningModel = "HRTF";
  54962. this._switchPanningModel();
  54963. };
  54964. Sound.prototype.switchPanningModelToEqualPower = function () {
  54965. this._panningModel = "equalpower";
  54966. this._switchPanningModel();
  54967. };
  54968. Sound.prototype._switchPanningModel = function () {
  54969. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  54970. this._soundPanner.panningModel = this._panningModel;
  54971. }
  54972. };
  54973. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  54974. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  54975. if (this._isOutputConnected) {
  54976. this._ouputAudioNode.disconnect();
  54977. }
  54978. this._ouputAudioNode.connect(soundTrackAudioNode);
  54979. this._isOutputConnected = true;
  54980. }
  54981. };
  54982. /**
  54983. * Transform this sound into a directional source
  54984. * @param coneInnerAngle Size of the inner cone in degree
  54985. * @param coneOuterAngle Size of the outer cone in degree
  54986. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  54987. */
  54988. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  54989. if (coneOuterAngle < coneInnerAngle) {
  54990. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  54991. return;
  54992. }
  54993. this._coneInnerAngle = coneInnerAngle;
  54994. this._coneOuterAngle = coneOuterAngle;
  54995. this._coneOuterGain = coneOuterGain;
  54996. this._isDirectional = true;
  54997. if (this.isPlaying && this.loop) {
  54998. this.stop();
  54999. this.play();
  55000. }
  55001. };
  55002. Sound.prototype.setPosition = function (newPosition) {
  55003. this._position = newPosition;
  55004. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  55005. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  55006. }
  55007. };
  55008. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  55009. this._localDirection = newLocalDirection;
  55010. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  55011. this._updateDirection();
  55012. }
  55013. };
  55014. Sound.prototype._updateDirection = function () {
  55015. if (!this._connectedMesh || !this._soundPanner) {
  55016. return;
  55017. }
  55018. var mat = this._connectedMesh.getWorldMatrix();
  55019. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  55020. direction.normalize();
  55021. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  55022. };
  55023. Sound.prototype.updateDistanceFromListener = function () {
  55024. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  55025. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  55026. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  55027. }
  55028. };
  55029. Sound.prototype.setAttenuationFunction = function (callback) {
  55030. this._customAttenuationFunction = callback;
  55031. };
  55032. /**
  55033. * Play the sound
  55034. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  55035. * @param offset (optional) Start the sound setting it at a specific time
  55036. */
  55037. Sound.prototype.play = function (time, offset) {
  55038. var _this = this;
  55039. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  55040. try {
  55041. if (this._startOffset < 0) {
  55042. time = -this._startOffset;
  55043. this._startOffset = 0;
  55044. }
  55045. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  55046. if (!this._soundSource || !this._streamingSource) {
  55047. if (this.spatialSound && this._soundPanner) {
  55048. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  55049. if (this._isDirectional) {
  55050. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  55051. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  55052. this._soundPanner.coneOuterGain = this._coneOuterGain;
  55053. if (this._connectedMesh) {
  55054. this._updateDirection();
  55055. }
  55056. else {
  55057. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  55058. }
  55059. }
  55060. }
  55061. }
  55062. if (this._streaming) {
  55063. if (!this._streamingSource) {
  55064. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  55065. this._htmlAudioElement.onended = function () { _this._onended(); };
  55066. this._htmlAudioElement.playbackRate = this._playbackRate;
  55067. }
  55068. this._streamingSource.disconnect();
  55069. this._streamingSource.connect(this._inputAudioNode);
  55070. this._htmlAudioElement.play();
  55071. }
  55072. else {
  55073. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  55074. this._soundSource.buffer = this._audioBuffer;
  55075. this._soundSource.connect(this._inputAudioNode);
  55076. this._soundSource.loop = this.loop;
  55077. this._soundSource.playbackRate.value = this._playbackRate;
  55078. this._soundSource.onended = function () { _this._onended(); };
  55079. if (this._soundSource.buffer) {
  55080. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  55081. }
  55082. }
  55083. this._startTime = startTime;
  55084. this.isPlaying = true;
  55085. this.isPaused = false;
  55086. }
  55087. catch (ex) {
  55088. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  55089. }
  55090. }
  55091. };
  55092. Sound.prototype._onended = function () {
  55093. this.isPlaying = false;
  55094. if (this.onended) {
  55095. this.onended();
  55096. }
  55097. };
  55098. /**
  55099. * Stop the sound
  55100. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  55101. */
  55102. Sound.prototype.stop = function (time) {
  55103. if (this.isPlaying) {
  55104. if (this._streaming) {
  55105. this._htmlAudioElement.pause();
  55106. // Test needed for Firefox or it will generate an Invalid State Error
  55107. if (this._htmlAudioElement.currentTime > 0) {
  55108. this._htmlAudioElement.currentTime = 0;
  55109. }
  55110. }
  55111. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  55112. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  55113. this._soundSource.stop(stopTime);
  55114. this._soundSource.onended = function () { };
  55115. if (!this.isPaused) {
  55116. this._startOffset = 0;
  55117. }
  55118. }
  55119. this.isPlaying = false;
  55120. }
  55121. };
  55122. Sound.prototype.pause = function () {
  55123. if (this.isPlaying) {
  55124. this.isPaused = true;
  55125. if (this._streaming) {
  55126. this._htmlAudioElement.pause();
  55127. }
  55128. else if (BABYLON.Engine.audioEngine.audioContext) {
  55129. this.stop(0);
  55130. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  55131. }
  55132. }
  55133. };
  55134. Sound.prototype.setVolume = function (newVolume, time) {
  55135. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  55136. if (time && BABYLON.Engine.audioEngine.audioContext) {
  55137. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  55138. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  55139. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  55140. }
  55141. else {
  55142. this._soundGain.gain.value = newVolume;
  55143. }
  55144. }
  55145. this._volume = newVolume;
  55146. };
  55147. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  55148. this._playbackRate = newPlaybackRate;
  55149. if (this.isPlaying) {
  55150. if (this._streaming) {
  55151. this._htmlAudioElement.playbackRate = this._playbackRate;
  55152. }
  55153. else if (this._soundSource) {
  55154. this._soundSource.playbackRate.value = this._playbackRate;
  55155. }
  55156. }
  55157. };
  55158. Sound.prototype.getVolume = function () {
  55159. return this._volume;
  55160. };
  55161. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  55162. var _this = this;
  55163. if (this._connectedMesh && this._registerFunc) {
  55164. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55165. this._registerFunc = null;
  55166. }
  55167. this._connectedMesh = meshToConnectTo;
  55168. if (!this.spatialSound) {
  55169. this.spatialSound = true;
  55170. this._createSpatialParameters();
  55171. if (this.isPlaying && this.loop) {
  55172. this.stop();
  55173. this.play();
  55174. }
  55175. }
  55176. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  55177. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  55178. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  55179. };
  55180. Sound.prototype.detachFromMesh = function () {
  55181. if (this._connectedMesh && this._registerFunc) {
  55182. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55183. this._registerFunc = null;
  55184. this._connectedMesh = null;
  55185. }
  55186. };
  55187. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  55188. if (!node.getBoundingInfo) {
  55189. return;
  55190. }
  55191. var mesh = node;
  55192. var boundingInfo = mesh.getBoundingInfo();
  55193. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  55194. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  55195. this._updateDirection();
  55196. }
  55197. };
  55198. Sound.prototype.clone = function () {
  55199. var _this = this;
  55200. if (!this._streaming) {
  55201. var setBufferAndRun = function () {
  55202. if (_this._isReadyToPlay) {
  55203. clonedSound._audioBuffer = _this.getAudioBuffer();
  55204. clonedSound._isReadyToPlay = true;
  55205. if (clonedSound.autoplay) {
  55206. clonedSound.play();
  55207. }
  55208. }
  55209. else {
  55210. window.setTimeout(setBufferAndRun, 300);
  55211. }
  55212. };
  55213. var currentOptions = {
  55214. autoplay: this.autoplay, loop: this.loop,
  55215. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  55216. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  55217. refDistance: this.refDistance, distanceModel: this.distanceModel
  55218. };
  55219. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  55220. if (this.useCustomAttenuation) {
  55221. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  55222. }
  55223. clonedSound.setPosition(this._position);
  55224. clonedSound.setPlaybackRate(this._playbackRate);
  55225. setBufferAndRun();
  55226. return clonedSound;
  55227. }
  55228. else {
  55229. return null;
  55230. }
  55231. };
  55232. Sound.prototype.getAudioBuffer = function () {
  55233. return this._audioBuffer;
  55234. };
  55235. Sound.prototype.serialize = function () {
  55236. var serializationObject = {
  55237. name: this.name,
  55238. url: this.name,
  55239. autoplay: this.autoplay,
  55240. loop: this.loop,
  55241. volume: this._volume,
  55242. spatialSound: this.spatialSound,
  55243. maxDistance: this.maxDistance,
  55244. rolloffFactor: this.rolloffFactor,
  55245. refDistance: this.refDistance,
  55246. distanceModel: this.distanceModel,
  55247. playbackRate: this._playbackRate,
  55248. panningModel: this._panningModel,
  55249. soundTrackId: this.soundTrackId
  55250. };
  55251. if (this.spatialSound) {
  55252. if (this._connectedMesh)
  55253. serializationObject.connectedMeshId = this._connectedMesh.id;
  55254. serializationObject.position = this._position.asArray();
  55255. serializationObject.refDistance = this.refDistance;
  55256. serializationObject.distanceModel = this.distanceModel;
  55257. serializationObject.isDirectional = this._isDirectional;
  55258. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  55259. serializationObject.coneInnerAngle = this._coneInnerAngle;
  55260. serializationObject.coneOuterAngle = this._coneOuterAngle;
  55261. serializationObject.coneOuterGain = this._coneOuterGain;
  55262. }
  55263. return serializationObject;
  55264. };
  55265. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  55266. var soundName = parsedSound.name;
  55267. var soundUrl;
  55268. if (parsedSound.url) {
  55269. soundUrl = rootUrl + parsedSound.url;
  55270. }
  55271. else {
  55272. soundUrl = rootUrl + soundName;
  55273. }
  55274. var options = {
  55275. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  55276. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  55277. rolloffFactor: parsedSound.rolloffFactor,
  55278. refDistance: parsedSound.refDistance,
  55279. distanceModel: parsedSound.distanceModel,
  55280. playbackRate: parsedSound.playbackRate
  55281. };
  55282. var newSound;
  55283. if (!sourceSound) {
  55284. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  55285. scene._addPendingData(newSound);
  55286. }
  55287. else {
  55288. var setBufferAndRun = function () {
  55289. if (sourceSound._isReadyToPlay) {
  55290. newSound._audioBuffer = sourceSound.getAudioBuffer();
  55291. newSound._isReadyToPlay = true;
  55292. if (newSound.autoplay) {
  55293. newSound.play();
  55294. }
  55295. }
  55296. else {
  55297. window.setTimeout(setBufferAndRun, 300);
  55298. }
  55299. };
  55300. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  55301. setBufferAndRun();
  55302. }
  55303. if (parsedSound.position) {
  55304. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  55305. newSound.setPosition(soundPosition);
  55306. }
  55307. if (parsedSound.isDirectional) {
  55308. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  55309. if (parsedSound.localDirectionToMesh) {
  55310. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  55311. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  55312. }
  55313. }
  55314. if (parsedSound.connectedMeshId) {
  55315. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  55316. if (connectedMesh) {
  55317. newSound.attachToMesh(connectedMesh);
  55318. }
  55319. }
  55320. return newSound;
  55321. };
  55322. return Sound;
  55323. }());
  55324. BABYLON.Sound = Sound;
  55325. })(BABYLON || (BABYLON = {}));
  55326. //# sourceMappingURL=babylon.sound.js.map
  55327. var BABYLON;
  55328. (function (BABYLON) {
  55329. var SoundTrack = /** @class */ (function () {
  55330. function SoundTrack(scene, options) {
  55331. this.id = -1;
  55332. this._isMainTrack = false;
  55333. this._isInitialized = false;
  55334. this._scene = scene;
  55335. this.soundCollection = new Array();
  55336. this._options = options;
  55337. if (!this._isMainTrack) {
  55338. this._scene.soundTracks.push(this);
  55339. this.id = this._scene.soundTracks.length - 1;
  55340. }
  55341. }
  55342. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  55343. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55344. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  55345. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  55346. if (this._options) {
  55347. if (this._options.volume) {
  55348. this._outputAudioNode.gain.value = this._options.volume;
  55349. }
  55350. if (this._options.mainTrack) {
  55351. this._isMainTrack = this._options.mainTrack;
  55352. }
  55353. }
  55354. this._isInitialized = true;
  55355. }
  55356. };
  55357. SoundTrack.prototype.dispose = function () {
  55358. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55359. if (this._connectedAnalyser) {
  55360. this._connectedAnalyser.stopDebugCanvas();
  55361. }
  55362. while (this.soundCollection.length) {
  55363. this.soundCollection[0].dispose();
  55364. }
  55365. if (this._outputAudioNode) {
  55366. this._outputAudioNode.disconnect();
  55367. }
  55368. this._outputAudioNode = null;
  55369. }
  55370. };
  55371. SoundTrack.prototype.AddSound = function (sound) {
  55372. if (!this._isInitialized) {
  55373. this._initializeSoundTrackAudioGraph();
  55374. }
  55375. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55376. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  55377. }
  55378. if (sound.soundTrackId) {
  55379. if (sound.soundTrackId === -1) {
  55380. this._scene.mainSoundTrack.RemoveSound(sound);
  55381. }
  55382. else {
  55383. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  55384. }
  55385. }
  55386. this.soundCollection.push(sound);
  55387. sound.soundTrackId = this.id;
  55388. };
  55389. SoundTrack.prototype.RemoveSound = function (sound) {
  55390. var index = this.soundCollection.indexOf(sound);
  55391. if (index !== -1) {
  55392. this.soundCollection.splice(index, 1);
  55393. }
  55394. };
  55395. SoundTrack.prototype.setVolume = function (newVolume) {
  55396. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55397. this._outputAudioNode.gain.value = newVolume;
  55398. }
  55399. };
  55400. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  55401. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55402. for (var i = 0; i < this.soundCollection.length; i++) {
  55403. this.soundCollection[i].switchPanningModelToHRTF();
  55404. }
  55405. }
  55406. };
  55407. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  55408. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55409. for (var i = 0; i < this.soundCollection.length; i++) {
  55410. this.soundCollection[i].switchPanningModelToEqualPower();
  55411. }
  55412. }
  55413. };
  55414. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  55415. if (this._connectedAnalyser) {
  55416. this._connectedAnalyser.stopDebugCanvas();
  55417. }
  55418. this._connectedAnalyser = analyser;
  55419. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55420. this._outputAudioNode.disconnect();
  55421. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  55422. }
  55423. };
  55424. return SoundTrack;
  55425. }());
  55426. BABYLON.SoundTrack = SoundTrack;
  55427. })(BABYLON || (BABYLON = {}));
  55428. //# sourceMappingURL=babylon.soundtrack.js.map
  55429. var BABYLON;
  55430. (function (BABYLON) {
  55431. var Analyser = /** @class */ (function () {
  55432. function Analyser(scene) {
  55433. this.SMOOTHING = 0.75;
  55434. this.FFT_SIZE = 512;
  55435. this.BARGRAPHAMPLITUDE = 256;
  55436. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  55437. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  55438. this._scene = scene;
  55439. this._audioEngine = BABYLON.Engine.audioEngine;
  55440. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  55441. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  55442. this._webAudioAnalyser.minDecibels = -140;
  55443. this._webAudioAnalyser.maxDecibels = 0;
  55444. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  55445. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  55446. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  55447. }
  55448. }
  55449. Analyser.prototype.getFrequencyBinCount = function () {
  55450. if (this._audioEngine.canUseWebAudio) {
  55451. return this._webAudioAnalyser.frequencyBinCount;
  55452. }
  55453. else {
  55454. return 0;
  55455. }
  55456. };
  55457. Analyser.prototype.getByteFrequencyData = function () {
  55458. if (this._audioEngine.canUseWebAudio) {
  55459. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55460. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55461. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  55462. }
  55463. return this._byteFreqs;
  55464. };
  55465. Analyser.prototype.getByteTimeDomainData = function () {
  55466. if (this._audioEngine.canUseWebAudio) {
  55467. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55468. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55469. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  55470. }
  55471. return this._byteTime;
  55472. };
  55473. Analyser.prototype.getFloatFrequencyData = function () {
  55474. if (this._audioEngine.canUseWebAudio) {
  55475. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55476. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55477. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  55478. }
  55479. return this._floatFreqs;
  55480. };
  55481. Analyser.prototype.drawDebugCanvas = function () {
  55482. var _this = this;
  55483. if (this._audioEngine.canUseWebAudio) {
  55484. if (!this._debugCanvas) {
  55485. this._debugCanvas = document.createElement("canvas");
  55486. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  55487. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  55488. this._debugCanvas.style.position = "absolute";
  55489. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  55490. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  55491. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  55492. document.body.appendChild(this._debugCanvas);
  55493. this._registerFunc = function () {
  55494. _this.drawDebugCanvas();
  55495. };
  55496. this._scene.registerBeforeRender(this._registerFunc);
  55497. }
  55498. if (this._registerFunc && this._debugCanvasContext) {
  55499. var workingArray = this.getByteFrequencyData();
  55500. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  55501. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  55502. // Draw the frequency domain chart.
  55503. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  55504. var value = workingArray[i];
  55505. var percent = value / this.BARGRAPHAMPLITUDE;
  55506. var height = this.DEBUGCANVASSIZE.height * percent;
  55507. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  55508. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  55509. var hue = i / this.getFrequencyBinCount() * 360;
  55510. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  55511. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  55512. }
  55513. }
  55514. }
  55515. };
  55516. Analyser.prototype.stopDebugCanvas = function () {
  55517. if (this._debugCanvas) {
  55518. if (this._registerFunc) {
  55519. this._scene.unregisterBeforeRender(this._registerFunc);
  55520. this._registerFunc = null;
  55521. }
  55522. document.body.removeChild(this._debugCanvas);
  55523. this._debugCanvas = null;
  55524. this._debugCanvasContext = null;
  55525. }
  55526. };
  55527. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  55528. if (this._audioEngine.canUseWebAudio) {
  55529. inputAudioNode.connect(this._webAudioAnalyser);
  55530. this._webAudioAnalyser.connect(outputAudioNode);
  55531. }
  55532. };
  55533. Analyser.prototype.dispose = function () {
  55534. if (this._audioEngine.canUseWebAudio) {
  55535. this._webAudioAnalyser.disconnect();
  55536. }
  55537. };
  55538. return Analyser;
  55539. }());
  55540. BABYLON.Analyser = Analyser;
  55541. })(BABYLON || (BABYLON = {}));
  55542. //# sourceMappingURL=babylon.analyser.js.map
  55543. var BABYLON;
  55544. (function (BABYLON) {
  55545. var CubeTexture = /** @class */ (function (_super) {
  55546. __extends(CubeTexture, _super);
  55547. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  55548. if (extensions === void 0) { extensions = null; }
  55549. if (noMipmap === void 0) { noMipmap = false; }
  55550. if (files === void 0) { files = null; }
  55551. if (onLoad === void 0) { onLoad = null; }
  55552. if (onError === void 0) { onError = null; }
  55553. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  55554. if (prefiltered === void 0) { prefiltered = false; }
  55555. if (forcedExtension === void 0) { forcedExtension = null; }
  55556. var _this = _super.call(this, scene) || this;
  55557. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  55558. _this.name = rootUrl;
  55559. _this.url = rootUrl;
  55560. _this._noMipmap = noMipmap;
  55561. _this.hasAlpha = false;
  55562. _this._format = format;
  55563. _this._prefiltered = prefiltered;
  55564. _this.isCube = true;
  55565. _this._textureMatrix = BABYLON.Matrix.Identity();
  55566. if (prefiltered) {
  55567. _this.gammaSpace = false;
  55568. }
  55569. if (!rootUrl && !files) {
  55570. return _this;
  55571. }
  55572. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  55573. var lastDot = rootUrl.lastIndexOf(".");
  55574. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  55575. var isDDS = (extension === ".dds");
  55576. if (!files) {
  55577. if (!isDDS && !extensions) {
  55578. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  55579. }
  55580. files = [];
  55581. if (extensions) {
  55582. for (var index = 0; index < extensions.length; index++) {
  55583. files.push(rootUrl + extensions[index]);
  55584. }
  55585. }
  55586. }
  55587. _this._files = files;
  55588. if (!_this._texture) {
  55589. if (!scene.useDelayedTextureLoading) {
  55590. if (prefiltered) {
  55591. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  55592. }
  55593. else {
  55594. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  55595. }
  55596. }
  55597. else {
  55598. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  55599. }
  55600. }
  55601. else if (onLoad) {
  55602. if (_this._texture.isReady) {
  55603. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  55604. }
  55605. else {
  55606. _this._texture.onLoadedObservable.add(onLoad);
  55607. }
  55608. }
  55609. return _this;
  55610. }
  55611. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  55612. return new CubeTexture("", scene, null, noMipmap, files);
  55613. };
  55614. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  55615. if (forcedExtension === void 0) { forcedExtension = null; }
  55616. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  55617. };
  55618. // Methods
  55619. CubeTexture.prototype.delayLoad = function () {
  55620. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  55621. return;
  55622. }
  55623. var scene = this.getScene();
  55624. if (!scene) {
  55625. return;
  55626. }
  55627. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  55628. this._texture = this._getFromCache(this.url, this._noMipmap);
  55629. if (!this._texture) {
  55630. if (this._prefiltered) {
  55631. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  55632. }
  55633. else {
  55634. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  55635. }
  55636. }
  55637. };
  55638. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  55639. return this._textureMatrix;
  55640. };
  55641. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  55642. this._textureMatrix = value;
  55643. };
  55644. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  55645. var texture = BABYLON.SerializationHelper.Parse(function () {
  55646. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  55647. }, parsedTexture, scene);
  55648. // Animations
  55649. if (parsedTexture.animations) {
  55650. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  55651. var parsedAnimation = parsedTexture.animations[animationIndex];
  55652. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  55653. }
  55654. }
  55655. return texture;
  55656. };
  55657. CubeTexture.prototype.clone = function () {
  55658. var _this = this;
  55659. return BABYLON.SerializationHelper.Clone(function () {
  55660. var scene = _this.getScene();
  55661. if (!scene) {
  55662. return _this;
  55663. }
  55664. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  55665. }, this);
  55666. };
  55667. return CubeTexture;
  55668. }(BABYLON.BaseTexture));
  55669. BABYLON.CubeTexture = CubeTexture;
  55670. })(BABYLON || (BABYLON = {}));
  55671. //# sourceMappingURL=babylon.cubeTexture.js.map
  55672. var BABYLON;
  55673. (function (BABYLON) {
  55674. var RenderTargetTexture = /** @class */ (function (_super) {
  55675. __extends(RenderTargetTexture, _super);
  55676. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  55677. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  55678. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55679. if (isCube === void 0) { isCube = false; }
  55680. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55681. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  55682. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  55683. if (isMulti === void 0) { isMulti = false; }
  55684. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  55685. _this.isCube = isCube;
  55686. /**
  55687. * Use this list to define the list of mesh you want to render.
  55688. */
  55689. _this.renderList = new Array();
  55690. _this.renderParticles = true;
  55691. _this.renderSprites = false;
  55692. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  55693. _this.ignoreCameraViewport = false;
  55694. // Events
  55695. /**
  55696. * An event triggered when the texture is unbind.
  55697. * @type {BABYLON.Observable}
  55698. */
  55699. _this.onBeforeBindObservable = new BABYLON.Observable();
  55700. /**
  55701. * An event triggered when the texture is unbind.
  55702. * @type {BABYLON.Observable}
  55703. */
  55704. _this.onAfterUnbindObservable = new BABYLON.Observable();
  55705. /**
  55706. * An event triggered before rendering the texture
  55707. * @type {BABYLON.Observable}
  55708. */
  55709. _this.onBeforeRenderObservable = new BABYLON.Observable();
  55710. /**
  55711. * An event triggered after rendering the texture
  55712. * @type {BABYLON.Observable}
  55713. */
  55714. _this.onAfterRenderObservable = new BABYLON.Observable();
  55715. /**
  55716. * An event triggered after the texture clear
  55717. * @type {BABYLON.Observable}
  55718. */
  55719. _this.onClearObservable = new BABYLON.Observable();
  55720. _this._currentRefreshId = -1;
  55721. _this._refreshRate = 1;
  55722. _this._samples = 1;
  55723. scene = _this.getScene();
  55724. if (!scene) {
  55725. return _this;
  55726. }
  55727. _this._engine = scene.getEngine();
  55728. _this.name = name;
  55729. _this.isRenderTarget = true;
  55730. _this._initialSizeParameter = size;
  55731. _this._processSizeParameter(size);
  55732. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  55733. });
  55734. _this._generateMipMaps = generateMipMaps ? true : false;
  55735. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  55736. // Rendering groups
  55737. _this._renderingManager = new BABYLON.RenderingManager(scene);
  55738. if (isMulti) {
  55739. return _this;
  55740. }
  55741. _this._renderTargetOptions = {
  55742. generateMipMaps: generateMipMaps,
  55743. type: type,
  55744. samplingMode: samplingMode,
  55745. generateDepthBuffer: generateDepthBuffer,
  55746. generateStencilBuffer: generateStencilBuffer
  55747. };
  55748. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  55749. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55750. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55751. }
  55752. if (isCube) {
  55753. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  55754. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  55755. _this._textureMatrix = BABYLON.Matrix.Identity();
  55756. }
  55757. else {
  55758. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  55759. }
  55760. return _this;
  55761. }
  55762. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  55763. get: function () {
  55764. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  55765. },
  55766. enumerable: true,
  55767. configurable: true
  55768. });
  55769. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  55770. get: function () {
  55771. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  55772. },
  55773. enumerable: true,
  55774. configurable: true
  55775. });
  55776. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  55777. get: function () {
  55778. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  55779. },
  55780. enumerable: true,
  55781. configurable: true
  55782. });
  55783. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  55784. set: function (callback) {
  55785. if (this._onAfterUnbindObserver) {
  55786. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  55787. }
  55788. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  55789. },
  55790. enumerable: true,
  55791. configurable: true
  55792. });
  55793. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  55794. set: function (callback) {
  55795. if (this._onBeforeRenderObserver) {
  55796. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  55797. }
  55798. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  55799. },
  55800. enumerable: true,
  55801. configurable: true
  55802. });
  55803. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  55804. set: function (callback) {
  55805. if (this._onAfterRenderObserver) {
  55806. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  55807. }
  55808. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  55809. },
  55810. enumerable: true,
  55811. configurable: true
  55812. });
  55813. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  55814. set: function (callback) {
  55815. if (this._onClearObserver) {
  55816. this.onClearObservable.remove(this._onClearObserver);
  55817. }
  55818. this._onClearObserver = this.onClearObservable.add(callback);
  55819. },
  55820. enumerable: true,
  55821. configurable: true
  55822. });
  55823. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  55824. get: function () {
  55825. return this._renderTargetOptions;
  55826. },
  55827. enumerable: true,
  55828. configurable: true
  55829. });
  55830. RenderTargetTexture.prototype._onRatioRescale = function () {
  55831. if (this._sizeRatio) {
  55832. this.resize(this._initialSizeParameter);
  55833. }
  55834. };
  55835. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  55836. if (size.ratio) {
  55837. this._sizeRatio = size.ratio;
  55838. this._size = {
  55839. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  55840. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  55841. };
  55842. }
  55843. else {
  55844. this._size = size;
  55845. }
  55846. };
  55847. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  55848. get: function () {
  55849. return this._samples;
  55850. },
  55851. set: function (value) {
  55852. if (this._samples === value) {
  55853. return;
  55854. }
  55855. var scene = this.getScene();
  55856. if (!scene) {
  55857. return;
  55858. }
  55859. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  55860. },
  55861. enumerable: true,
  55862. configurable: true
  55863. });
  55864. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  55865. this._currentRefreshId = -1;
  55866. };
  55867. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  55868. get: function () {
  55869. return this._refreshRate;
  55870. },
  55871. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  55872. set: function (value) {
  55873. this._refreshRate = value;
  55874. this.resetRefreshCounter();
  55875. },
  55876. enumerable: true,
  55877. configurable: true
  55878. });
  55879. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  55880. if (!this._postProcessManager) {
  55881. var scene = this.getScene();
  55882. if (!scene) {
  55883. return;
  55884. }
  55885. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  55886. this._postProcesses = new Array();
  55887. }
  55888. this._postProcesses.push(postProcess);
  55889. this._postProcesses[0].autoClear = false;
  55890. };
  55891. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  55892. if (!this._postProcesses) {
  55893. return;
  55894. }
  55895. if (dispose) {
  55896. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  55897. var postProcess = _a[_i];
  55898. postProcess.dispose();
  55899. }
  55900. }
  55901. this._postProcesses = [];
  55902. };
  55903. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  55904. if (!this._postProcesses) {
  55905. return;
  55906. }
  55907. var index = this._postProcesses.indexOf(postProcess);
  55908. if (index === -1) {
  55909. return;
  55910. }
  55911. this._postProcesses.splice(index, 1);
  55912. if (this._postProcesses.length > 0) {
  55913. this._postProcesses[0].autoClear = false;
  55914. }
  55915. };
  55916. RenderTargetTexture.prototype._shouldRender = function () {
  55917. if (this._currentRefreshId === -1) {
  55918. this._currentRefreshId = 1;
  55919. return true;
  55920. }
  55921. if (this.refreshRate === this._currentRefreshId) {
  55922. this._currentRefreshId = 1;
  55923. return true;
  55924. }
  55925. this._currentRefreshId++;
  55926. return false;
  55927. };
  55928. RenderTargetTexture.prototype.getRenderSize = function () {
  55929. if (this._size.width) {
  55930. return this._size.width;
  55931. }
  55932. return this._size;
  55933. };
  55934. RenderTargetTexture.prototype.getRenderWidth = function () {
  55935. if (this._size.width) {
  55936. return this._size.width;
  55937. }
  55938. return this._size;
  55939. };
  55940. RenderTargetTexture.prototype.getRenderHeight = function () {
  55941. if (this._size.width) {
  55942. return this._size.height;
  55943. }
  55944. return this._size;
  55945. };
  55946. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  55947. get: function () {
  55948. return true;
  55949. },
  55950. enumerable: true,
  55951. configurable: true
  55952. });
  55953. RenderTargetTexture.prototype.scale = function (ratio) {
  55954. var newSize = this.getRenderSize() * ratio;
  55955. this.resize(newSize);
  55956. };
  55957. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  55958. if (this.isCube) {
  55959. return this._textureMatrix;
  55960. }
  55961. return _super.prototype.getReflectionTextureMatrix.call(this);
  55962. };
  55963. RenderTargetTexture.prototype.resize = function (size) {
  55964. this.releaseInternalTexture();
  55965. var scene = this.getScene();
  55966. if (!scene) {
  55967. return;
  55968. }
  55969. this._processSizeParameter(size);
  55970. if (this.isCube) {
  55971. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  55972. }
  55973. else {
  55974. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  55975. }
  55976. };
  55977. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  55978. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  55979. if (dumpForDebug === void 0) { dumpForDebug = false; }
  55980. var scene = this.getScene();
  55981. if (!scene) {
  55982. return;
  55983. }
  55984. var engine = scene.getEngine();
  55985. if (this.useCameraPostProcesses !== undefined) {
  55986. useCameraPostProcess = this.useCameraPostProcesses;
  55987. }
  55988. if (this._waitingRenderList) {
  55989. this.renderList = [];
  55990. for (var index = 0; index < this._waitingRenderList.length; index++) {
  55991. var id = this._waitingRenderList[index];
  55992. var mesh_1 = scene.getMeshByID(id);
  55993. if (mesh_1) {
  55994. this.renderList.push(mesh_1);
  55995. }
  55996. }
  55997. delete this._waitingRenderList;
  55998. }
  55999. // Is predicate defined?
  56000. if (this.renderListPredicate) {
  56001. if (this.renderList) {
  56002. this.renderList.splice(0); // Clear previous renderList
  56003. }
  56004. else {
  56005. this.renderList = [];
  56006. }
  56007. var scene = this.getScene();
  56008. if (!scene) {
  56009. return;
  56010. }
  56011. var sceneMeshes = scene.meshes;
  56012. for (var index = 0; index < sceneMeshes.length; index++) {
  56013. var mesh = sceneMeshes[index];
  56014. if (this.renderListPredicate(mesh)) {
  56015. this.renderList.push(mesh);
  56016. }
  56017. }
  56018. }
  56019. this.onBeforeBindObservable.notifyObservers(this);
  56020. // Set custom projection.
  56021. // Needs to be before binding to prevent changing the aspect ratio.
  56022. var camera;
  56023. if (this.activeCamera) {
  56024. camera = this.activeCamera;
  56025. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  56026. if (this.activeCamera !== scene.activeCamera) {
  56027. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  56028. }
  56029. }
  56030. else {
  56031. camera = scene.activeCamera;
  56032. if (camera) {
  56033. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  56034. }
  56035. }
  56036. // Prepare renderingManager
  56037. this._renderingManager.reset();
  56038. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  56039. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  56040. var sceneRenderId = scene.getRenderId();
  56041. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  56042. var mesh = currentRenderList[meshIndex];
  56043. if (mesh) {
  56044. if (!mesh.isReady()) {
  56045. // Reset _currentRefreshId
  56046. this.resetRefreshCounter();
  56047. continue;
  56048. }
  56049. mesh._preActivateForIntermediateRendering(sceneRenderId);
  56050. var isMasked = void 0;
  56051. if (!this.renderList && camera) {
  56052. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  56053. }
  56054. else {
  56055. isMasked = false;
  56056. }
  56057. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  56058. mesh._activate(sceneRenderId);
  56059. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  56060. var subMesh = mesh.subMeshes[subIndex];
  56061. scene._activeIndices.addCount(subMesh.indexCount, false);
  56062. this._renderingManager.dispatch(subMesh, mesh);
  56063. }
  56064. }
  56065. }
  56066. }
  56067. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  56068. var particleSystem = scene.particleSystems[particleIndex];
  56069. var emitter = particleSystem.emitter;
  56070. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  56071. continue;
  56072. }
  56073. if (currentRenderList.indexOf(emitter) >= 0) {
  56074. this._renderingManager.dispatchParticles(particleSystem);
  56075. }
  56076. }
  56077. if (this.isCube) {
  56078. for (var face = 0; face < 6; face++) {
  56079. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  56080. scene.incrementRenderId();
  56081. scene.resetCachedMaterial();
  56082. }
  56083. }
  56084. else {
  56085. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  56086. }
  56087. this.onAfterUnbindObservable.notifyObservers(this);
  56088. if (scene.activeCamera) {
  56089. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  56090. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  56091. }
  56092. engine.setViewport(scene.activeCamera.viewport);
  56093. }
  56094. scene.resetCachedMaterial();
  56095. };
  56096. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  56097. var minimum = 128;
  56098. var x = renderDimension * scale;
  56099. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  56100. // Ensure we don't exceed the render dimension (while staying POT)
  56101. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  56102. };
  56103. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  56104. var _this = this;
  56105. if (!this._texture) {
  56106. return;
  56107. }
  56108. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  56109. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  56110. });
  56111. };
  56112. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  56113. var scene = this.getScene();
  56114. if (!scene) {
  56115. return;
  56116. }
  56117. var engine = scene.getEngine();
  56118. if (!this._texture) {
  56119. return;
  56120. }
  56121. // Bind
  56122. if (this._postProcessManager) {
  56123. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  56124. }
  56125. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  56126. if (this._texture) {
  56127. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  56128. }
  56129. }
  56130. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  56131. // Clear
  56132. if (this.onClearObservable.hasObservers()) {
  56133. this.onClearObservable.notifyObservers(engine);
  56134. }
  56135. else {
  56136. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  56137. }
  56138. if (!this._doNotChangeAspectRatio) {
  56139. scene.updateTransformMatrix(true);
  56140. }
  56141. // Render
  56142. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  56143. if (this._postProcessManager) {
  56144. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  56145. }
  56146. else if (useCameraPostProcess) {
  56147. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  56148. }
  56149. if (!this._doNotChangeAspectRatio) {
  56150. scene.updateTransformMatrix(true);
  56151. }
  56152. // Dump ?
  56153. if (dumpForDebug) {
  56154. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  56155. }
  56156. // Unbind
  56157. if (!this.isCube || faceIndex === 5) {
  56158. if (this.isCube) {
  56159. if (faceIndex === 5) {
  56160. engine.generateMipMapsForCubemap(this._texture);
  56161. }
  56162. }
  56163. this.unbindFrameBuffer(engine, faceIndex);
  56164. }
  56165. else {
  56166. this.onAfterRenderObservable.notifyObservers(faceIndex);
  56167. }
  56168. };
  56169. /**
  56170. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  56171. * This allowed control for front to back rendering or reversly depending of the special needs.
  56172. *
  56173. * @param renderingGroupId The rendering group id corresponding to its index
  56174. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  56175. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  56176. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  56177. */
  56178. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  56179. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  56180. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  56181. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  56182. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  56183. };
  56184. /**
  56185. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  56186. *
  56187. * @param renderingGroupId The rendering group id corresponding to its index
  56188. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  56189. */
  56190. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  56191. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  56192. };
  56193. RenderTargetTexture.prototype.clone = function () {
  56194. var textureSize = this.getSize();
  56195. 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);
  56196. // Base texture
  56197. newTexture.hasAlpha = this.hasAlpha;
  56198. newTexture.level = this.level;
  56199. // RenderTarget Texture
  56200. newTexture.coordinatesMode = this.coordinatesMode;
  56201. if (this.renderList) {
  56202. newTexture.renderList = this.renderList.slice(0);
  56203. }
  56204. return newTexture;
  56205. };
  56206. RenderTargetTexture.prototype.serialize = function () {
  56207. if (!this.name) {
  56208. return null;
  56209. }
  56210. var serializationObject = _super.prototype.serialize.call(this);
  56211. serializationObject.renderTargetSize = this.getRenderSize();
  56212. serializationObject.renderList = [];
  56213. if (this.renderList) {
  56214. for (var index = 0; index < this.renderList.length; index++) {
  56215. serializationObject.renderList.push(this.renderList[index].id);
  56216. }
  56217. }
  56218. return serializationObject;
  56219. };
  56220. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  56221. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  56222. var objBuffer = this.getInternalTexture();
  56223. var scene = this.getScene();
  56224. if (objBuffer && scene) {
  56225. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  56226. }
  56227. };
  56228. RenderTargetTexture.prototype.dispose = function () {
  56229. if (this._postProcessManager) {
  56230. this._postProcessManager.dispose();
  56231. this._postProcessManager = null;
  56232. }
  56233. this.clearPostProcesses(true);
  56234. if (this._resizeObserver) {
  56235. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  56236. this._resizeObserver = null;
  56237. }
  56238. this.renderList = null;
  56239. // Remove from custom render targets
  56240. var scene = this.getScene();
  56241. if (!scene) {
  56242. return;
  56243. }
  56244. var index = scene.customRenderTargets.indexOf(this);
  56245. if (index >= 0) {
  56246. scene.customRenderTargets.splice(index, 1);
  56247. }
  56248. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  56249. var camera = _a[_i];
  56250. index = camera.customRenderTargets.indexOf(this);
  56251. if (index >= 0) {
  56252. camera.customRenderTargets.splice(index, 1);
  56253. }
  56254. }
  56255. _super.prototype.dispose.call(this);
  56256. };
  56257. RenderTargetTexture.prototype._rebuild = function () {
  56258. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  56259. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  56260. }
  56261. if (this._postProcessManager) {
  56262. this._postProcessManager._rebuild();
  56263. }
  56264. };
  56265. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  56266. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  56267. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  56268. return RenderTargetTexture;
  56269. }(BABYLON.Texture));
  56270. BABYLON.RenderTargetTexture = RenderTargetTexture;
  56271. })(BABYLON || (BABYLON = {}));
  56272. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  56273. var BABYLON;
  56274. (function (BABYLON) {
  56275. ;
  56276. var MultiRenderTarget = /** @class */ (function (_super) {
  56277. __extends(MultiRenderTarget, _super);
  56278. function MultiRenderTarget(name, size, count, scene, options) {
  56279. var _this = this;
  56280. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  56281. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  56282. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  56283. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  56284. _this._engine = scene.getEngine();
  56285. if (!_this.isSupported) {
  56286. _this.dispose();
  56287. return;
  56288. }
  56289. var types = [];
  56290. var samplingModes = [];
  56291. for (var i = 0; i < count; i++) {
  56292. if (options && options.types && options.types[i] !== undefined) {
  56293. types.push(options.types[i]);
  56294. }
  56295. else {
  56296. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  56297. }
  56298. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  56299. samplingModes.push(options.samplingModes[i]);
  56300. }
  56301. else {
  56302. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56303. }
  56304. }
  56305. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  56306. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  56307. _this._size = size;
  56308. _this._multiRenderTargetOptions = {
  56309. samplingModes: samplingModes,
  56310. generateMipMaps: generateMipMaps,
  56311. generateDepthBuffer: generateDepthBuffer,
  56312. generateStencilBuffer: generateStencilBuffer,
  56313. generateDepthTexture: generateDepthTexture,
  56314. types: types,
  56315. textureCount: count
  56316. };
  56317. _this._createInternalTextures();
  56318. _this._createTextures();
  56319. return _this;
  56320. }
  56321. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  56322. get: function () {
  56323. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  56324. },
  56325. enumerable: true,
  56326. configurable: true
  56327. });
  56328. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  56329. get: function () {
  56330. return this._textures;
  56331. },
  56332. enumerable: true,
  56333. configurable: true
  56334. });
  56335. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  56336. get: function () {
  56337. return this._textures[this._textures.length - 1];
  56338. },
  56339. enumerable: true,
  56340. configurable: true
  56341. });
  56342. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  56343. set: function (wrap) {
  56344. if (this._textures) {
  56345. for (var i = 0; i < this._textures.length; i++) {
  56346. this._textures[i].wrapU = wrap;
  56347. }
  56348. }
  56349. },
  56350. enumerable: true,
  56351. configurable: true
  56352. });
  56353. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  56354. set: function (wrap) {
  56355. if (this._textures) {
  56356. for (var i = 0; i < this._textures.length; i++) {
  56357. this._textures[i].wrapV = wrap;
  56358. }
  56359. }
  56360. },
  56361. enumerable: true,
  56362. configurable: true
  56363. });
  56364. MultiRenderTarget.prototype._rebuild = function () {
  56365. this.releaseInternalTextures();
  56366. this._createInternalTextures();
  56367. for (var i = 0; i < this._internalTextures.length; i++) {
  56368. var texture = this._textures[i];
  56369. texture._texture = this._internalTextures[i];
  56370. }
  56371. // Keeps references to frame buffer and stencil/depth buffer
  56372. this._texture = this._internalTextures[0];
  56373. };
  56374. MultiRenderTarget.prototype._createInternalTextures = function () {
  56375. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  56376. };
  56377. MultiRenderTarget.prototype._createTextures = function () {
  56378. this._textures = [];
  56379. for (var i = 0; i < this._internalTextures.length; i++) {
  56380. var texture = new BABYLON.Texture(null, this.getScene());
  56381. texture._texture = this._internalTextures[i];
  56382. this._textures.push(texture);
  56383. }
  56384. // Keeps references to frame buffer and stencil/depth buffer
  56385. this._texture = this._internalTextures[0];
  56386. };
  56387. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  56388. get: function () {
  56389. return this._samples;
  56390. },
  56391. set: function (value) {
  56392. if (this._samples === value) {
  56393. return;
  56394. }
  56395. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  56396. },
  56397. enumerable: true,
  56398. configurable: true
  56399. });
  56400. MultiRenderTarget.prototype.resize = function (size) {
  56401. this.releaseInternalTextures();
  56402. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  56403. this._createInternalTextures();
  56404. };
  56405. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  56406. var _this = this;
  56407. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  56408. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  56409. });
  56410. };
  56411. MultiRenderTarget.prototype.dispose = function () {
  56412. this.releaseInternalTextures();
  56413. _super.prototype.dispose.call(this);
  56414. };
  56415. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  56416. if (!this._internalTextures) {
  56417. return;
  56418. }
  56419. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  56420. if (this._internalTextures[i] !== undefined) {
  56421. this._internalTextures[i].dispose();
  56422. this._internalTextures.splice(i, 1);
  56423. }
  56424. }
  56425. };
  56426. return MultiRenderTarget;
  56427. }(BABYLON.RenderTargetTexture));
  56428. BABYLON.MultiRenderTarget = MultiRenderTarget;
  56429. })(BABYLON || (BABYLON = {}));
  56430. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  56431. var BABYLON;
  56432. (function (BABYLON) {
  56433. var MirrorTexture = /** @class */ (function (_super) {
  56434. __extends(MirrorTexture, _super);
  56435. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  56436. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56437. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  56438. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  56439. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  56440. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  56441. _this._transformMatrix = BABYLON.Matrix.Zero();
  56442. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  56443. _this._adaptiveBlurKernel = 0;
  56444. _this._blurKernelX = 0;
  56445. _this._blurKernelY = 0;
  56446. _this._blurRatio = 1.0;
  56447. _this.ignoreCameraViewport = true;
  56448. _this.onBeforeRenderObservable.add(function () {
  56449. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  56450. _this._savedViewMatrix = scene.getViewMatrix();
  56451. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  56452. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  56453. scene.clipPlane = _this.mirrorPlane;
  56454. scene.getEngine().cullBackFaces = false;
  56455. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  56456. });
  56457. _this.onAfterRenderObservable.add(function () {
  56458. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  56459. scene.getEngine().cullBackFaces = true;
  56460. scene._mirroredCameraPosition = null;
  56461. delete scene.clipPlane;
  56462. });
  56463. return _this;
  56464. }
  56465. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  56466. get: function () {
  56467. return this._blurRatio;
  56468. },
  56469. set: function (value) {
  56470. if (this._blurRatio === value) {
  56471. return;
  56472. }
  56473. this._blurRatio = value;
  56474. this._preparePostProcesses();
  56475. },
  56476. enumerable: true,
  56477. configurable: true
  56478. });
  56479. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  56480. set: function (value) {
  56481. this._adaptiveBlurKernel = value;
  56482. this._autoComputeBlurKernel();
  56483. },
  56484. enumerable: true,
  56485. configurable: true
  56486. });
  56487. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  56488. set: function (value) {
  56489. this.blurKernelX = value;
  56490. this.blurKernelY = value;
  56491. },
  56492. enumerable: true,
  56493. configurable: true
  56494. });
  56495. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  56496. get: function () {
  56497. return this._blurKernelX;
  56498. },
  56499. set: function (value) {
  56500. if (this._blurKernelX === value) {
  56501. return;
  56502. }
  56503. this._blurKernelX = value;
  56504. this._preparePostProcesses();
  56505. },
  56506. enumerable: true,
  56507. configurable: true
  56508. });
  56509. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  56510. get: function () {
  56511. return this._blurKernelY;
  56512. },
  56513. set: function (value) {
  56514. if (this._blurKernelY === value) {
  56515. return;
  56516. }
  56517. this._blurKernelY = value;
  56518. this._preparePostProcesses();
  56519. },
  56520. enumerable: true,
  56521. configurable: true
  56522. });
  56523. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  56524. var engine = this.getScene().getEngine();
  56525. var dw = this.getRenderWidth() / engine.getRenderWidth();
  56526. var dh = this.getRenderHeight() / engine.getRenderHeight();
  56527. this.blurKernelX = this._adaptiveBlurKernel * dw;
  56528. this.blurKernelY = this._adaptiveBlurKernel * dh;
  56529. };
  56530. MirrorTexture.prototype._onRatioRescale = function () {
  56531. if (this._sizeRatio) {
  56532. this.resize(this._initialSizeParameter);
  56533. if (!this._adaptiveBlurKernel) {
  56534. this._preparePostProcesses();
  56535. }
  56536. }
  56537. if (this._adaptiveBlurKernel) {
  56538. this._autoComputeBlurKernel();
  56539. }
  56540. };
  56541. MirrorTexture.prototype._preparePostProcesses = function () {
  56542. this.clearPostProcesses(true);
  56543. if (this._blurKernelX && this._blurKernelY) {
  56544. var engine = this.getScene().getEngine();
  56545. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  56546. 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);
  56547. this._blurX.autoClear = false;
  56548. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  56549. this._blurX.inputTexture = this._texture;
  56550. }
  56551. else {
  56552. this._blurX.alwaysForcePOT = true;
  56553. }
  56554. 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);
  56555. this._blurY.autoClear = false;
  56556. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  56557. this.addPostProcess(this._blurX);
  56558. this.addPostProcess(this._blurY);
  56559. }
  56560. else {
  56561. if (this._blurY) {
  56562. this.removePostProcess(this._blurY);
  56563. this._blurY.dispose();
  56564. this._blurY = null;
  56565. }
  56566. if (this._blurX) {
  56567. this.removePostProcess(this._blurX);
  56568. this._blurX.dispose();
  56569. this._blurX = null;
  56570. }
  56571. }
  56572. };
  56573. MirrorTexture.prototype.clone = function () {
  56574. var scene = this.getScene();
  56575. if (!scene) {
  56576. return this;
  56577. }
  56578. var textureSize = this.getSize();
  56579. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  56580. // Base texture
  56581. newTexture.hasAlpha = this.hasAlpha;
  56582. newTexture.level = this.level;
  56583. // Mirror Texture
  56584. newTexture.mirrorPlane = this.mirrorPlane.clone();
  56585. if (this.renderList) {
  56586. newTexture.renderList = this.renderList.slice(0);
  56587. }
  56588. return newTexture;
  56589. };
  56590. MirrorTexture.prototype.serialize = function () {
  56591. if (!this.name) {
  56592. return null;
  56593. }
  56594. var serializationObject = _super.prototype.serialize.call(this);
  56595. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  56596. return serializationObject;
  56597. };
  56598. return MirrorTexture;
  56599. }(BABYLON.RenderTargetTexture));
  56600. BABYLON.MirrorTexture = MirrorTexture;
  56601. })(BABYLON || (BABYLON = {}));
  56602. //# sourceMappingURL=babylon.mirrorTexture.js.map
  56603. var BABYLON;
  56604. (function (BABYLON) {
  56605. /**
  56606. * Creates a refraction texture used by refraction channel of the standard material.
  56607. * @param name the texture name
  56608. * @param size size of the underlying texture
  56609. * @param scene root scene
  56610. */
  56611. var RefractionTexture = /** @class */ (function (_super) {
  56612. __extends(RefractionTexture, _super);
  56613. function RefractionTexture(name, size, scene, generateMipMaps) {
  56614. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  56615. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  56616. _this.depth = 2.0;
  56617. _this.onBeforeRenderObservable.add(function () {
  56618. scene.clipPlane = _this.refractionPlane;
  56619. });
  56620. _this.onAfterRenderObservable.add(function () {
  56621. delete scene.clipPlane;
  56622. });
  56623. return _this;
  56624. }
  56625. RefractionTexture.prototype.clone = function () {
  56626. var scene = this.getScene();
  56627. if (!scene) {
  56628. return this;
  56629. }
  56630. var textureSize = this.getSize();
  56631. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  56632. // Base texture
  56633. newTexture.hasAlpha = this.hasAlpha;
  56634. newTexture.level = this.level;
  56635. // Refraction Texture
  56636. newTexture.refractionPlane = this.refractionPlane.clone();
  56637. if (this.renderList) {
  56638. newTexture.renderList = this.renderList.slice(0);
  56639. }
  56640. newTexture.depth = this.depth;
  56641. return newTexture;
  56642. };
  56643. RefractionTexture.prototype.serialize = function () {
  56644. if (!this.name) {
  56645. return null;
  56646. }
  56647. var serializationObject = _super.prototype.serialize.call(this);
  56648. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  56649. serializationObject.depth = this.depth;
  56650. return serializationObject;
  56651. };
  56652. return RefractionTexture;
  56653. }(BABYLON.RenderTargetTexture));
  56654. BABYLON.RefractionTexture = RefractionTexture;
  56655. })(BABYLON || (BABYLON = {}));
  56656. //# sourceMappingURL=babylon.refractionTexture.js.map
  56657. var BABYLON;
  56658. (function (BABYLON) {
  56659. var DynamicTexture = /** @class */ (function (_super) {
  56660. __extends(DynamicTexture, _super);
  56661. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  56662. if (scene === void 0) { scene = null; }
  56663. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56664. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  56665. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  56666. _this.name = name;
  56667. _this._engine = _this.getScene().getEngine();
  56668. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56669. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56670. _this._generateMipMaps = generateMipMaps;
  56671. if (options.getContext) {
  56672. _this._canvas = options;
  56673. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  56674. }
  56675. else {
  56676. _this._canvas = document.createElement("canvas");
  56677. if (options.width) {
  56678. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  56679. }
  56680. else {
  56681. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  56682. }
  56683. }
  56684. var textureSize = _this.getSize();
  56685. _this._canvas.width = textureSize.width;
  56686. _this._canvas.height = textureSize.height;
  56687. _this._context = _this._canvas.getContext("2d");
  56688. return _this;
  56689. }
  56690. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  56691. get: function () {
  56692. return true;
  56693. },
  56694. enumerable: true,
  56695. configurable: true
  56696. });
  56697. DynamicTexture.prototype._recreate = function (textureSize) {
  56698. this._canvas.width = textureSize.width;
  56699. this._canvas.height = textureSize.height;
  56700. this.releaseInternalTexture();
  56701. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  56702. };
  56703. DynamicTexture.prototype.scale = function (ratio) {
  56704. var textureSize = this.getSize();
  56705. textureSize.width *= ratio;
  56706. textureSize.height *= ratio;
  56707. this._recreate(textureSize);
  56708. };
  56709. DynamicTexture.prototype.scaleTo = function (width, height) {
  56710. var textureSize = this.getSize();
  56711. textureSize.width = width;
  56712. textureSize.height = height;
  56713. this._recreate(textureSize);
  56714. };
  56715. DynamicTexture.prototype.getContext = function () {
  56716. return this._context;
  56717. };
  56718. DynamicTexture.prototype.clear = function () {
  56719. var size = this.getSize();
  56720. this._context.fillRect(0, 0, size.width, size.height);
  56721. };
  56722. DynamicTexture.prototype.update = function (invertY) {
  56723. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  56724. };
  56725. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  56726. if (update === void 0) { update = true; }
  56727. var size = this.getSize();
  56728. if (clearColor) {
  56729. this._context.fillStyle = clearColor;
  56730. this._context.fillRect(0, 0, size.width, size.height);
  56731. }
  56732. this._context.font = font;
  56733. if (x === null || x === undefined) {
  56734. var textSize = this._context.measureText(text);
  56735. x = (size.width - textSize.width) / 2;
  56736. }
  56737. if (y === null || y === undefined) {
  56738. var fontSize = parseInt((font.replace(/\D/g, '')));
  56739. ;
  56740. y = (size.height / 2) + (fontSize / 3.65);
  56741. }
  56742. this._context.fillStyle = color;
  56743. this._context.fillText(text, x, y);
  56744. if (update) {
  56745. this.update(invertY);
  56746. }
  56747. };
  56748. DynamicTexture.prototype.clone = function () {
  56749. var scene = this.getScene();
  56750. if (!scene) {
  56751. return this;
  56752. }
  56753. var textureSize = this.getSize();
  56754. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  56755. // Base texture
  56756. newTexture.hasAlpha = this.hasAlpha;
  56757. newTexture.level = this.level;
  56758. // Dynamic Texture
  56759. newTexture.wrapU = this.wrapU;
  56760. newTexture.wrapV = this.wrapV;
  56761. return newTexture;
  56762. };
  56763. DynamicTexture.prototype._rebuild = function () {
  56764. this.update();
  56765. };
  56766. return DynamicTexture;
  56767. }(BABYLON.Texture));
  56768. BABYLON.DynamicTexture = DynamicTexture;
  56769. })(BABYLON || (BABYLON = {}));
  56770. //# sourceMappingURL=babylon.dynamicTexture.js.map
  56771. var BABYLON;
  56772. (function (BABYLON) {
  56773. var VideoTexture = /** @class */ (function (_super) {
  56774. __extends(VideoTexture, _super);
  56775. /**
  56776. * Creates a video texture.
  56777. * Sample : https://doc.babylonjs.com/how_to/video_texture
  56778. * @param {string | null} name optional name, will detect from video source, if not defined
  56779. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  56780. * @param {BABYLON.Scene} scene is obviously the current scene.
  56781. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  56782. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  56783. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  56784. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  56785. */
  56786. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  56787. if (generateMipMaps === void 0) { generateMipMaps = false; }
  56788. if (invertY === void 0) { invertY = false; }
  56789. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56790. if (settings === void 0) { settings = {
  56791. autoPlay: true,
  56792. loop: true,
  56793. autoUpdateTexture: true,
  56794. }; }
  56795. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  56796. _this._createInternalTexture = function () {
  56797. if (_this._texture != null) {
  56798. return;
  56799. }
  56800. if (!_this._engine.needPOTTextures ||
  56801. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  56802. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56803. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56804. }
  56805. else {
  56806. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56807. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56808. _this._generateMipMaps = false;
  56809. }
  56810. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  56811. _this._texture.isReady = true;
  56812. _this._updateInternalTexture();
  56813. };
  56814. _this.reset = function () {
  56815. if (_this._texture == null) {
  56816. return;
  56817. }
  56818. _this._texture.dispose();
  56819. _this._texture = null;
  56820. };
  56821. _this._updateInternalTexture = function (e) {
  56822. if (_this._texture == null || !_this._texture.isReady) {
  56823. return;
  56824. }
  56825. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  56826. return;
  56827. }
  56828. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  56829. };
  56830. _this._engine = _this.getScene().getEngine();
  56831. _this._generateMipMaps = generateMipMaps;
  56832. _this._samplingMode = samplingMode;
  56833. _this.autoUpdateTexture = settings.autoUpdateTexture;
  56834. _this.name = name || _this._getName(src);
  56835. _this.video = _this._getVideo(src);
  56836. if (settings.autoPlay !== undefined) {
  56837. _this.video.autoplay = settings.autoPlay;
  56838. }
  56839. if (settings.loop !== undefined) {
  56840. _this.video.loop = settings.loop;
  56841. }
  56842. _this.video.addEventListener("canplay", _this._createInternalTexture);
  56843. _this.video.addEventListener("paused", _this._updateInternalTexture);
  56844. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  56845. _this.video.addEventListener("emptied", _this.reset);
  56846. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  56847. _this._createInternalTexture();
  56848. }
  56849. return _this;
  56850. }
  56851. VideoTexture.prototype._getName = function (src) {
  56852. if (src instanceof HTMLVideoElement) {
  56853. return src.currentSrc;
  56854. }
  56855. if (typeof src === "object") {
  56856. return src.toString();
  56857. }
  56858. return src;
  56859. };
  56860. ;
  56861. VideoTexture.prototype._getVideo = function (src) {
  56862. if (src instanceof HTMLVideoElement) {
  56863. return src;
  56864. }
  56865. var video = document.createElement("video");
  56866. if (typeof src === "string") {
  56867. video.src = src;
  56868. }
  56869. else {
  56870. src.forEach(function (url) {
  56871. var source = document.createElement("source");
  56872. source.src = url;
  56873. video.appendChild(source);
  56874. });
  56875. }
  56876. return video;
  56877. };
  56878. ;
  56879. /**
  56880. * Internal method to initiate `update`.
  56881. */
  56882. VideoTexture.prototype._rebuild = function () {
  56883. this.update();
  56884. };
  56885. /**
  56886. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  56887. */
  56888. VideoTexture.prototype.update = function () {
  56889. if (!this.autoUpdateTexture) {
  56890. // Expecting user to call `updateTexture` manually
  56891. return;
  56892. }
  56893. this.updateTexture(true);
  56894. };
  56895. /**
  56896. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  56897. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  56898. */
  56899. VideoTexture.prototype.updateTexture = function (isVisible) {
  56900. if (!isVisible) {
  56901. return;
  56902. }
  56903. if (this.video.paused) {
  56904. return;
  56905. }
  56906. this._updateInternalTexture();
  56907. };
  56908. /**
  56909. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  56910. * @param url New url.
  56911. */
  56912. VideoTexture.prototype.updateURL = function (url) {
  56913. this.video.src = url;
  56914. };
  56915. VideoTexture.prototype.dispose = function () {
  56916. _super.prototype.dispose.call(this);
  56917. this.video.removeEventListener("canplay", this._createInternalTexture);
  56918. this.video.removeEventListener("paused", this._updateInternalTexture);
  56919. this.video.removeEventListener("seeked", this._updateInternalTexture);
  56920. this.video.removeEventListener("emptied", this.reset);
  56921. };
  56922. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  56923. var video = document.createElement("video");
  56924. var constraintsDeviceId;
  56925. if (constraints && constraints.deviceId) {
  56926. constraintsDeviceId = {
  56927. exact: constraints.deviceId,
  56928. };
  56929. }
  56930. navigator.getUserMedia =
  56931. navigator.getUserMedia ||
  56932. navigator.webkitGetUserMedia ||
  56933. navigator.mozGetUserMedia ||
  56934. navigator.msGetUserMedia;
  56935. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  56936. if (navigator.getUserMedia) {
  56937. navigator.getUserMedia({
  56938. video: {
  56939. deviceId: constraintsDeviceId,
  56940. width: {
  56941. min: (constraints && constraints.minWidth) || 256,
  56942. max: (constraints && constraints.maxWidth) || 640,
  56943. },
  56944. height: {
  56945. min: (constraints && constraints.minHeight) || 256,
  56946. max: (constraints && constraints.maxHeight) || 480,
  56947. },
  56948. },
  56949. }, function (stream) {
  56950. if (video.mozSrcObject !== undefined) {
  56951. // hack for Firefox < 19
  56952. video.mozSrcObject = stream;
  56953. }
  56954. else {
  56955. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  56956. }
  56957. video.play();
  56958. if (onReady) {
  56959. onReady(new VideoTexture("video", video, scene, true, true));
  56960. }
  56961. }, function (e) {
  56962. BABYLON.Tools.Error(e.name);
  56963. });
  56964. }
  56965. };
  56966. return VideoTexture;
  56967. }(BABYLON.Texture));
  56968. BABYLON.VideoTexture = VideoTexture;
  56969. })(BABYLON || (BABYLON = {}));
  56970. //# sourceMappingURL=babylon.videoTexture.js.map
  56971. var BABYLON;
  56972. (function (BABYLON) {
  56973. var RawTexture = /** @class */ (function (_super) {
  56974. __extends(RawTexture, _super);
  56975. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  56976. if (generateMipMaps === void 0) { generateMipMaps = true; }
  56977. if (invertY === void 0) { invertY = false; }
  56978. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56979. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56980. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  56981. _this.format = format;
  56982. _this._engine = scene.getEngine();
  56983. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  56984. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56985. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56986. return _this;
  56987. }
  56988. RawTexture.prototype.update = function (data) {
  56989. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  56990. };
  56991. // Statics
  56992. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  56993. if (generateMipMaps === void 0) { generateMipMaps = true; }
  56994. if (invertY === void 0) { invertY = false; }
  56995. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56996. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  56997. };
  56998. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  56999. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57000. if (invertY === void 0) { invertY = false; }
  57001. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57002. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  57003. };
  57004. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57005. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57006. if (invertY === void 0) { invertY = false; }
  57007. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57008. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  57009. };
  57010. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  57011. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57012. if (invertY === void 0) { invertY = false; }
  57013. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57014. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57015. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  57016. };
  57017. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  57018. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57019. if (invertY === void 0) { invertY = false; }
  57020. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57021. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57022. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  57023. };
  57024. return RawTexture;
  57025. }(BABYLON.Texture));
  57026. BABYLON.RawTexture = RawTexture;
  57027. })(BABYLON || (BABYLON = {}));
  57028. //# sourceMappingURL=babylon.rawTexture.js.map
  57029. var BABYLON;
  57030. (function (BABYLON) {
  57031. /**
  57032. * PostProcess can be used to apply a shader to a texture after it has been rendered
  57033. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  57034. */
  57035. var PostProcess = /** @class */ (function () {
  57036. /**
  57037. * Creates a new instance of @see PostProcess
  57038. * @param name The name of the PostProcess.
  57039. * @param fragmentUrl The url of the fragment shader to be used.
  57040. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  57041. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  57042. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  57043. * @param camera The camera to apply the render pass to.
  57044. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  57045. * @param engine The engine which the post process will be applied. (default: current engine)
  57046. * @param reusable If the post process can be reused on the same frame. (default: false)
  57047. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  57048. * @param textureType Type of textures used when performing the post process. (default: 0)
  57049. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  57050. * @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
  57051. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  57052. */
  57053. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  57054. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  57055. if (defines === void 0) { defines = null; }
  57056. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57057. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  57058. if (blockCompilation === void 0) { blockCompilation = false; }
  57059. this.name = name;
  57060. /**
  57061. * Width of the texture to apply the post process on
  57062. */
  57063. this.width = -1;
  57064. /**
  57065. * Height of the texture to apply the post process on
  57066. */
  57067. this.height = -1;
  57068. /**
  57069. * If the buffer needs to be cleared before applying the post process. (default: true)
  57070. * Should be set to false if shader will overwrite all previous pixels.
  57071. */
  57072. this.autoClear = true;
  57073. /**
  57074. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  57075. */
  57076. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  57077. /**
  57078. * Animations to be used for the post processing
  57079. */
  57080. this.animations = new Array();
  57081. /**
  57082. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  57083. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  57084. */
  57085. this.enablePixelPerfectMode = false;
  57086. /**
  57087. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  57088. */
  57089. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  57090. /**
  57091. * Force textures to be a power of two (default: false)
  57092. */
  57093. this.alwaysForcePOT = false;
  57094. /**
  57095. * Number of sample textures (default: 1)
  57096. */
  57097. this.samples = 1;
  57098. /**
  57099. * Modify the scale of the post process to be the same as the viewport (default: false)
  57100. */
  57101. this.adaptScaleToCurrentViewport = false;
  57102. this._reusable = false;
  57103. /**
  57104. * Smart array of input and output textures for the post process.
  57105. */
  57106. this._textures = new BABYLON.SmartArray(2);
  57107. /**
  57108. * The index in _textures that corresponds to the output texture.
  57109. */
  57110. this._currentRenderTextureInd = 0;
  57111. this._scaleRatio = new BABYLON.Vector2(1, 1);
  57112. this._texelSize = BABYLON.Vector2.Zero();
  57113. // Events
  57114. /**
  57115. * An event triggered when the postprocess is activated.
  57116. * @type {BABYLON.Observable}
  57117. */
  57118. this.onActivateObservable = new BABYLON.Observable();
  57119. /**
  57120. * An event triggered when the postprocess changes its size.
  57121. * @type {BABYLON.Observable}
  57122. */
  57123. this.onSizeChangedObservable = new BABYLON.Observable();
  57124. /**
  57125. * An event triggered when the postprocess applies its effect.
  57126. * @type {BABYLON.Observable}
  57127. */
  57128. this.onApplyObservable = new BABYLON.Observable();
  57129. /**
  57130. * An event triggered before rendering the postprocess
  57131. * @type {BABYLON.Observable}
  57132. */
  57133. this.onBeforeRenderObservable = new BABYLON.Observable();
  57134. /**
  57135. * An event triggered after rendering the postprocess
  57136. * @type {BABYLON.Observable}
  57137. */
  57138. this.onAfterRenderObservable = new BABYLON.Observable();
  57139. if (camera != null) {
  57140. this._camera = camera;
  57141. this._scene = camera.getScene();
  57142. camera.attachPostProcess(this);
  57143. this._engine = this._scene.getEngine();
  57144. this._scene.postProcesses.push(this);
  57145. }
  57146. else if (engine) {
  57147. this._engine = engine;
  57148. this._engine.postProcesses.push(this);
  57149. }
  57150. this._options = options;
  57151. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  57152. this._reusable = reusable || false;
  57153. this._textureType = textureType;
  57154. this._samplers = samplers || [];
  57155. this._samplers.push("textureSampler");
  57156. this._fragmentUrl = fragmentUrl;
  57157. this._vertexUrl = vertexUrl;
  57158. this._parameters = parameters || [];
  57159. this._parameters.push("scale");
  57160. this._indexParameters = indexParameters;
  57161. if (!blockCompilation) {
  57162. this.updateEffect(defines);
  57163. }
  57164. }
  57165. Object.defineProperty(PostProcess.prototype, "onActivate", {
  57166. /**
  57167. * A function that is added to the onActivateObservable
  57168. */
  57169. set: function (callback) {
  57170. if (this._onActivateObserver) {
  57171. this.onActivateObservable.remove(this._onActivateObserver);
  57172. }
  57173. if (callback) {
  57174. this._onActivateObserver = this.onActivateObservable.add(callback);
  57175. }
  57176. },
  57177. enumerable: true,
  57178. configurable: true
  57179. });
  57180. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  57181. /**
  57182. * A function that is added to the onSizeChangedObservable
  57183. */
  57184. set: function (callback) {
  57185. if (this._onSizeChangedObserver) {
  57186. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  57187. }
  57188. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  57189. },
  57190. enumerable: true,
  57191. configurable: true
  57192. });
  57193. Object.defineProperty(PostProcess.prototype, "onApply", {
  57194. /**
  57195. * A function that is added to the onApplyObservable
  57196. */
  57197. set: function (callback) {
  57198. if (this._onApplyObserver) {
  57199. this.onApplyObservable.remove(this._onApplyObserver);
  57200. }
  57201. this._onApplyObserver = this.onApplyObservable.add(callback);
  57202. },
  57203. enumerable: true,
  57204. configurable: true
  57205. });
  57206. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  57207. /**
  57208. * A function that is added to the onBeforeRenderObservable
  57209. */
  57210. set: function (callback) {
  57211. if (this._onBeforeRenderObserver) {
  57212. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  57213. }
  57214. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  57215. },
  57216. enumerable: true,
  57217. configurable: true
  57218. });
  57219. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  57220. /**
  57221. * A function that is added to the onAfterRenderObservable
  57222. */
  57223. set: function (callback) {
  57224. if (this._onAfterRenderObserver) {
  57225. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  57226. }
  57227. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  57228. },
  57229. enumerable: true,
  57230. configurable: true
  57231. });
  57232. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  57233. /**
  57234. * 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
  57235. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  57236. */
  57237. get: function () {
  57238. return this._textures.data[this._currentRenderTextureInd];
  57239. },
  57240. set: function (value) {
  57241. this._forcedOutputTexture = value;
  57242. },
  57243. enumerable: true,
  57244. configurable: true
  57245. });
  57246. /**
  57247. * Gets the camera which post process is applied to.
  57248. * @returns The camera the post process is applied to.
  57249. */
  57250. PostProcess.prototype.getCamera = function () {
  57251. return this._camera;
  57252. };
  57253. Object.defineProperty(PostProcess.prototype, "texelSize", {
  57254. /**
  57255. * Gets the texel size of the postprocess.
  57256. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  57257. */
  57258. get: function () {
  57259. if (this._shareOutputWithPostProcess) {
  57260. return this._shareOutputWithPostProcess.texelSize;
  57261. }
  57262. if (this._forcedOutputTexture) {
  57263. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  57264. }
  57265. return this._texelSize;
  57266. },
  57267. enumerable: true,
  57268. configurable: true
  57269. });
  57270. /**
  57271. * Gets the engine which this post process belongs to.
  57272. * @returns The engine the post process was enabled with.
  57273. */
  57274. PostProcess.prototype.getEngine = function () {
  57275. return this._engine;
  57276. };
  57277. /**
  57278. * The effect that is created when initializing the post process.
  57279. * @returns The created effect corrisponding the the postprocess.
  57280. */
  57281. PostProcess.prototype.getEffect = function () {
  57282. return this._effect;
  57283. };
  57284. /**
  57285. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  57286. * @param postProcess The post process to share the output with.
  57287. * @returns This post process.
  57288. */
  57289. PostProcess.prototype.shareOutputWith = function (postProcess) {
  57290. this._disposeTextures();
  57291. this._shareOutputWithPostProcess = postProcess;
  57292. return this;
  57293. };
  57294. /**
  57295. * Updates the effect with the current post process compile time values and recompiles the shader.
  57296. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  57297. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  57298. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  57299. * @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
  57300. * @param onCompiled Called when the shader has been compiled.
  57301. * @param onError Called if there is an error when compiling a shader.
  57302. */
  57303. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  57304. if (defines === void 0) { defines = null; }
  57305. if (uniforms === void 0) { uniforms = null; }
  57306. if (samplers === void 0) { samplers = null; }
  57307. 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);
  57308. };
  57309. /**
  57310. * The post process is reusable if it can be used multiple times within one frame.
  57311. * @returns If the post process is reusable
  57312. */
  57313. PostProcess.prototype.isReusable = function () {
  57314. return this._reusable;
  57315. };
  57316. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  57317. PostProcess.prototype.markTextureDirty = function () {
  57318. this.width = -1;
  57319. };
  57320. /**
  57321. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  57322. * 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.
  57323. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  57324. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  57325. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  57326. */
  57327. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  57328. var _this = this;
  57329. if (sourceTexture === void 0) { sourceTexture = null; }
  57330. camera = camera || this._camera;
  57331. var scene = camera.getScene();
  57332. var engine = scene.getEngine();
  57333. var maxSize = engine.getCaps().maxTextureSize;
  57334. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  57335. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  57336. var desiredWidth = (this._options.width || requiredWidth);
  57337. var desiredHeight = this._options.height || requiredHeight;
  57338. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  57339. if (this.adaptScaleToCurrentViewport) {
  57340. var currentViewport = engine.currentViewport;
  57341. if (currentViewport) {
  57342. desiredWidth *= currentViewport.width;
  57343. desiredHeight *= currentViewport.height;
  57344. }
  57345. }
  57346. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  57347. if (!this._options.width) {
  57348. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  57349. }
  57350. if (!this._options.height) {
  57351. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  57352. }
  57353. }
  57354. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  57355. if (this._textures.length > 0) {
  57356. for (var i = 0; i < this._textures.length; i++) {
  57357. this._engine._releaseTexture(this._textures.data[i]);
  57358. }
  57359. this._textures.reset();
  57360. }
  57361. this.width = desiredWidth;
  57362. this.height = desiredHeight;
  57363. var textureSize = { width: this.width, height: this.height };
  57364. var textureOptions = {
  57365. generateMipMaps: false,
  57366. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  57367. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  57368. samplingMode: this.renderTargetSamplingMode,
  57369. type: this._textureType
  57370. };
  57371. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  57372. if (this._reusable) {
  57373. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  57374. }
  57375. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  57376. this.onSizeChangedObservable.notifyObservers(this);
  57377. }
  57378. this._textures.forEach(function (texture) {
  57379. if (texture.samples !== _this.samples) {
  57380. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  57381. }
  57382. });
  57383. }
  57384. var target;
  57385. if (this._shareOutputWithPostProcess) {
  57386. target = this._shareOutputWithPostProcess.inputTexture;
  57387. }
  57388. else if (this._forcedOutputTexture) {
  57389. target = this._forcedOutputTexture;
  57390. this.width = this._forcedOutputTexture.width;
  57391. this.height = this._forcedOutputTexture.height;
  57392. }
  57393. else {
  57394. target = this.inputTexture;
  57395. }
  57396. // Bind the input of this post process to be used as the output of the previous post process.
  57397. if (this.enablePixelPerfectMode) {
  57398. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  57399. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  57400. }
  57401. else {
  57402. this._scaleRatio.copyFromFloats(1, 1);
  57403. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  57404. }
  57405. this.onActivateObservable.notifyObservers(camera);
  57406. // Clear
  57407. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  57408. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  57409. }
  57410. if (this._reusable) {
  57411. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  57412. }
  57413. };
  57414. Object.defineProperty(PostProcess.prototype, "isSupported", {
  57415. /**
  57416. * If the post process is supported.
  57417. */
  57418. get: function () {
  57419. return this._effect.isSupported;
  57420. },
  57421. enumerable: true,
  57422. configurable: true
  57423. });
  57424. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  57425. /**
  57426. * The aspect ratio of the output texture.
  57427. */
  57428. get: function () {
  57429. if (this._shareOutputWithPostProcess) {
  57430. return this._shareOutputWithPostProcess.aspectRatio;
  57431. }
  57432. if (this._forcedOutputTexture) {
  57433. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  57434. }
  57435. return this.width / this.height;
  57436. },
  57437. enumerable: true,
  57438. configurable: true
  57439. });
  57440. /**
  57441. * Get a value indicating if the post-process is ready to be used
  57442. * @returns true if the post-process is ready (shader is compiled)
  57443. */
  57444. PostProcess.prototype.isReady = function () {
  57445. return this._effect && this._effect.isReady();
  57446. };
  57447. /**
  57448. * Binds all textures and uniforms to the shader, this will be run on every pass.
  57449. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  57450. */
  57451. PostProcess.prototype.apply = function () {
  57452. // Check
  57453. if (!this._effect || !this._effect.isReady())
  57454. return null;
  57455. // States
  57456. this._engine.enableEffect(this._effect);
  57457. this._engine.setState(false);
  57458. this._engine.setDepthBuffer(false);
  57459. this._engine.setDepthWrite(false);
  57460. // Alpha
  57461. this._engine.setAlphaMode(this.alphaMode);
  57462. if (this.alphaConstants) {
  57463. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  57464. }
  57465. // Bind the output texture of the preivous post process as the input to this post process.
  57466. var source;
  57467. if (this._shareOutputWithPostProcess) {
  57468. source = this._shareOutputWithPostProcess.inputTexture;
  57469. }
  57470. else if (this._forcedOutputTexture) {
  57471. source = this._forcedOutputTexture;
  57472. }
  57473. else {
  57474. source = this.inputTexture;
  57475. }
  57476. this._effect._bindTexture("textureSampler", source);
  57477. // Parameters
  57478. this._effect.setVector2("scale", this._scaleRatio);
  57479. this.onApplyObservable.notifyObservers(this._effect);
  57480. return this._effect;
  57481. };
  57482. PostProcess.prototype._disposeTextures = function () {
  57483. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  57484. return;
  57485. }
  57486. if (this._textures.length > 0) {
  57487. for (var i = 0; i < this._textures.length; i++) {
  57488. this._engine._releaseTexture(this._textures.data[i]);
  57489. }
  57490. }
  57491. this._textures.dispose();
  57492. };
  57493. /**
  57494. * Disposes the post process.
  57495. * @param camera The camera to dispose the post process on.
  57496. */
  57497. PostProcess.prototype.dispose = function (camera) {
  57498. camera = camera || this._camera;
  57499. this._disposeTextures();
  57500. if (this._scene) {
  57501. var index_1 = this._scene.postProcesses.indexOf(this);
  57502. if (index_1 !== -1) {
  57503. this._scene.postProcesses.splice(index_1, 1);
  57504. }
  57505. }
  57506. else {
  57507. var index_2 = this._engine.postProcesses.indexOf(this);
  57508. if (index_2 !== -1) {
  57509. this._engine.postProcesses.splice(index_2, 1);
  57510. }
  57511. }
  57512. if (!camera) {
  57513. return;
  57514. }
  57515. camera.detachPostProcess(this);
  57516. var index = camera._postProcesses.indexOf(this);
  57517. if (index === 0 && camera._postProcesses.length > 0) {
  57518. this._camera._postProcesses[0].markTextureDirty();
  57519. }
  57520. this.onActivateObservable.clear();
  57521. this.onAfterRenderObservable.clear();
  57522. this.onApplyObservable.clear();
  57523. this.onBeforeRenderObservable.clear();
  57524. this.onSizeChangedObservable.clear();
  57525. };
  57526. return PostProcess;
  57527. }());
  57528. BABYLON.PostProcess = PostProcess;
  57529. })(BABYLON || (BABYLON = {}));
  57530. //# sourceMappingURL=babylon.postProcess.js.map
  57531. var BABYLON;
  57532. (function (BABYLON) {
  57533. var PassPostProcess = /** @class */ (function (_super) {
  57534. __extends(PassPostProcess, _super);
  57535. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  57536. if (camera === void 0) { camera = null; }
  57537. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57538. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  57539. }
  57540. return PassPostProcess;
  57541. }(BABYLON.PostProcess));
  57542. BABYLON.PassPostProcess = PassPostProcess;
  57543. })(BABYLON || (BABYLON = {}));
  57544. //# sourceMappingURL=babylon.passPostProcess.js.map
  57545. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57546. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57547. s = arguments[i];
  57548. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57549. t[p] = s[p];
  57550. }
  57551. return t;
  57552. };
  57553. var BABYLON;
  57554. (function (BABYLON) {
  57555. /**
  57556. * Default implementation of @see IShadowGenerator.
  57557. * This is the main object responsible of generating shadows in the framework.
  57558. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  57559. */
  57560. var ShadowGenerator = /** @class */ (function () {
  57561. /**
  57562. * Creates a ShadowGenerator object.
  57563. * A ShadowGenerator is the required tool to use the shadows.
  57564. * Each light casting shadows needs to use its own ShadowGenerator.
  57565. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  57566. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  57567. * @param light The light object generating the shadows.
  57568. * @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.
  57569. */
  57570. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  57571. this._bias = 0.00005;
  57572. this._blurBoxOffset = 1;
  57573. this._blurScale = 2;
  57574. this._blurKernel = 1;
  57575. this._useKernelBlur = false;
  57576. this._filter = ShadowGenerator.FILTER_NONE;
  57577. this._darkness = 0;
  57578. this._transparencyShadow = false;
  57579. /**
  57580. * Controls the extent to which the shadows fade out at the edge of the frustum
  57581. * Used only by directionals and spots
  57582. */
  57583. this.frustumEdgeFalloff = 0;
  57584. /**
  57585. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  57586. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  57587. * It might on the other hand introduce peter panning.
  57588. */
  57589. this.forceBackFacesOnly = false;
  57590. this._lightDirection = BABYLON.Vector3.Zero();
  57591. this._viewMatrix = BABYLON.Matrix.Zero();
  57592. this._projectionMatrix = BABYLON.Matrix.Zero();
  57593. this._transformMatrix = BABYLON.Matrix.Zero();
  57594. this._currentFaceIndex = 0;
  57595. this._currentFaceIndexCache = 0;
  57596. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  57597. this._mapSize = mapSize;
  57598. this._light = light;
  57599. this._scene = light.getScene();
  57600. light._shadowGenerator = this;
  57601. // Texture type fallback from float to int if not supported.
  57602. var caps = this._scene.getEngine().getCaps();
  57603. if (!useFullFloatFirst) {
  57604. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  57605. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57606. }
  57607. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  57608. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  57609. }
  57610. else {
  57611. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  57612. }
  57613. }
  57614. else {
  57615. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  57616. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  57617. }
  57618. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  57619. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57620. }
  57621. else {
  57622. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  57623. }
  57624. }
  57625. this._initializeGenerator();
  57626. }
  57627. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  57628. /**
  57629. * Shadow generator mode None: no filtering applied.
  57630. */
  57631. get: function () {
  57632. return ShadowGenerator._FILTER_NONE;
  57633. },
  57634. enumerable: true,
  57635. configurable: true
  57636. });
  57637. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  57638. /**
  57639. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  57640. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  57641. */
  57642. get: function () {
  57643. return ShadowGenerator._FILTER_POISSONSAMPLING;
  57644. },
  57645. enumerable: true,
  57646. configurable: true
  57647. });
  57648. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  57649. /**
  57650. * Shadow generator mode ESM: Exponential Shadow Mapping.
  57651. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  57652. */
  57653. get: function () {
  57654. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  57655. },
  57656. enumerable: true,
  57657. configurable: true
  57658. });
  57659. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  57660. /**
  57661. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  57662. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  57663. */
  57664. get: function () {
  57665. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  57666. },
  57667. enumerable: true,
  57668. configurable: true
  57669. });
  57670. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  57671. /**
  57672. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  57673. * edge artifacts on steep falloff.
  57674. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  57675. */
  57676. get: function () {
  57677. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  57678. },
  57679. enumerable: true,
  57680. configurable: true
  57681. });
  57682. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  57683. /**
  57684. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  57685. * edge artifacts on steep falloff.
  57686. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  57687. */
  57688. get: function () {
  57689. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  57690. },
  57691. enumerable: true,
  57692. configurable: true
  57693. });
  57694. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  57695. /**
  57696. * Gets the bias: offset applied on the depth preventing acnea.
  57697. */
  57698. get: function () {
  57699. return this._bias;
  57700. },
  57701. /**
  57702. * Sets the bias: offset applied on the depth preventing acnea.
  57703. */
  57704. set: function (bias) {
  57705. this._bias = bias;
  57706. },
  57707. enumerable: true,
  57708. configurable: true
  57709. });
  57710. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  57711. /**
  57712. * Gets the blur box offset: offset applied during the blur pass.
  57713. * Only usefull if useKernelBlur = false
  57714. */
  57715. get: function () {
  57716. return this._blurBoxOffset;
  57717. },
  57718. /**
  57719. * Sets the blur box offset: offset applied during the blur pass.
  57720. * Only usefull if useKernelBlur = false
  57721. */
  57722. set: function (value) {
  57723. if (this._blurBoxOffset === value) {
  57724. return;
  57725. }
  57726. this._blurBoxOffset = value;
  57727. this._disposeBlurPostProcesses();
  57728. },
  57729. enumerable: true,
  57730. configurable: true
  57731. });
  57732. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  57733. /**
  57734. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  57735. * 2 means half of the size.
  57736. */
  57737. get: function () {
  57738. return this._blurScale;
  57739. },
  57740. /**
  57741. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  57742. * 2 means half of the size.
  57743. */
  57744. set: function (value) {
  57745. if (this._blurScale === value) {
  57746. return;
  57747. }
  57748. this._blurScale = value;
  57749. this._disposeBlurPostProcesses();
  57750. },
  57751. enumerable: true,
  57752. configurable: true
  57753. });
  57754. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  57755. /**
  57756. * Gets the blur kernel: kernel size of the blur pass.
  57757. * Only usefull if useKernelBlur = true
  57758. */
  57759. get: function () {
  57760. return this._blurKernel;
  57761. },
  57762. /**
  57763. * Sets the blur kernel: kernel size of the blur pass.
  57764. * Only usefull if useKernelBlur = true
  57765. */
  57766. set: function (value) {
  57767. if (this._blurKernel === value) {
  57768. return;
  57769. }
  57770. this._blurKernel = value;
  57771. this._disposeBlurPostProcesses();
  57772. },
  57773. enumerable: true,
  57774. configurable: true
  57775. });
  57776. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  57777. /**
  57778. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  57779. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  57780. */
  57781. get: function () {
  57782. return this._useKernelBlur;
  57783. },
  57784. /**
  57785. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  57786. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  57787. */
  57788. set: function (value) {
  57789. if (this._useKernelBlur === value) {
  57790. return;
  57791. }
  57792. this._useKernelBlur = value;
  57793. this._disposeBlurPostProcesses();
  57794. },
  57795. enumerable: true,
  57796. configurable: true
  57797. });
  57798. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  57799. /**
  57800. * Gets the depth scale used in ESM mode.
  57801. */
  57802. get: function () {
  57803. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  57804. },
  57805. /**
  57806. * Sets the depth scale used in ESM mode.
  57807. * This can override the scale stored on the light.
  57808. */
  57809. set: function (value) {
  57810. this._depthScale = value;
  57811. },
  57812. enumerable: true,
  57813. configurable: true
  57814. });
  57815. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  57816. /**
  57817. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  57818. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  57819. */
  57820. get: function () {
  57821. return this._filter;
  57822. },
  57823. /**
  57824. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  57825. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  57826. */
  57827. set: function (value) {
  57828. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  57829. if (this._light.needCube()) {
  57830. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  57831. this.useExponentialShadowMap = true;
  57832. return;
  57833. }
  57834. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  57835. this.useCloseExponentialShadowMap = true;
  57836. return;
  57837. }
  57838. }
  57839. if (this._filter === value) {
  57840. return;
  57841. }
  57842. this._filter = value;
  57843. this._disposeBlurPostProcesses();
  57844. this._applyFilterValues();
  57845. this._light._markMeshesAsLightDirty();
  57846. },
  57847. enumerable: true,
  57848. configurable: true
  57849. });
  57850. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  57851. /**
  57852. * Gets if the current filter is set to Poisson Sampling aka PCF.
  57853. */
  57854. get: function () {
  57855. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  57856. },
  57857. /**
  57858. * Sets the current filter to Poisson Sampling aka PCF.
  57859. */
  57860. set: function (value) {
  57861. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  57862. return;
  57863. }
  57864. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  57865. },
  57866. enumerable: true,
  57867. configurable: true
  57868. });
  57869. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  57870. /**
  57871. * Gets if the current filter is set to VSM.
  57872. * DEPRECATED. Should use useExponentialShadowMap instead.
  57873. */
  57874. get: function () {
  57875. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  57876. return this.useExponentialShadowMap;
  57877. },
  57878. /**
  57879. * Sets the current filter is to VSM.
  57880. * DEPRECATED. Should use useExponentialShadowMap instead.
  57881. */
  57882. set: function (value) {
  57883. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  57884. this.useExponentialShadowMap = value;
  57885. },
  57886. enumerable: true,
  57887. configurable: true
  57888. });
  57889. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  57890. /**
  57891. * Gets if the current filter is set to blurred VSM.
  57892. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  57893. */
  57894. get: function () {
  57895. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  57896. return this.useBlurExponentialShadowMap;
  57897. },
  57898. /**
  57899. * Sets the current filter is to blurred VSM.
  57900. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  57901. */
  57902. set: function (value) {
  57903. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  57904. this.useBlurExponentialShadowMap = value;
  57905. },
  57906. enumerable: true,
  57907. configurable: true
  57908. });
  57909. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  57910. /**
  57911. * Gets if the current filter is set to ESM.
  57912. */
  57913. get: function () {
  57914. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  57915. },
  57916. /**
  57917. * Sets the current filter is to ESM.
  57918. */
  57919. set: function (value) {
  57920. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  57921. return;
  57922. }
  57923. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  57924. },
  57925. enumerable: true,
  57926. configurable: true
  57927. });
  57928. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  57929. /**
  57930. * Gets if the current filter is set to filtered ESM.
  57931. */
  57932. get: function () {
  57933. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  57934. },
  57935. /**
  57936. * Gets if the current filter is set to filtered ESM.
  57937. */
  57938. set: function (value) {
  57939. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  57940. return;
  57941. }
  57942. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  57943. },
  57944. enumerable: true,
  57945. configurable: true
  57946. });
  57947. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  57948. /**
  57949. * Gets if the current filter is set to "close ESM" (using the inverse of the
  57950. * exponential to prevent steep falloff artifacts).
  57951. */
  57952. get: function () {
  57953. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  57954. },
  57955. /**
  57956. * Sets the current filter to "close ESM" (using the inverse of the
  57957. * exponential to prevent steep falloff artifacts).
  57958. */
  57959. set: function (value) {
  57960. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  57961. return;
  57962. }
  57963. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  57964. },
  57965. enumerable: true,
  57966. configurable: true
  57967. });
  57968. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  57969. /**
  57970. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  57971. * exponential to prevent steep falloff artifacts).
  57972. */
  57973. get: function () {
  57974. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  57975. },
  57976. /**
  57977. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  57978. * exponential to prevent steep falloff artifacts).
  57979. */
  57980. set: function (value) {
  57981. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  57982. return;
  57983. }
  57984. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  57985. },
  57986. enumerable: true,
  57987. configurable: true
  57988. });
  57989. /**
  57990. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  57991. * 0 means strongest and 1 would means no shadow.
  57992. * @returns the darkness.
  57993. */
  57994. ShadowGenerator.prototype.getDarkness = function () {
  57995. return this._darkness;
  57996. };
  57997. /**
  57998. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  57999. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  58000. * @returns the shadow generator allowing fluent coding.
  58001. */
  58002. ShadowGenerator.prototype.setDarkness = function (darkness) {
  58003. if (darkness >= 1.0)
  58004. this._darkness = 1.0;
  58005. else if (darkness <= 0.0)
  58006. this._darkness = 0.0;
  58007. else
  58008. this._darkness = darkness;
  58009. return this;
  58010. };
  58011. /**
  58012. * Sets the ability to have transparent shadow (boolean).
  58013. * @param transparent True if transparent else False
  58014. * @returns the shadow generator allowing fluent coding
  58015. */
  58016. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  58017. this._transparencyShadow = transparent;
  58018. return this;
  58019. };
  58020. /**
  58021. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  58022. * @returns The render target texture if present otherwise, null
  58023. */
  58024. ShadowGenerator.prototype.getShadowMap = function () {
  58025. return this._shadowMap;
  58026. };
  58027. /**
  58028. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  58029. * @returns The render target texture if the shadow map is present otherwise, null
  58030. */
  58031. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  58032. if (this._shadowMap2) {
  58033. return this._shadowMap2;
  58034. }
  58035. return this._shadowMap;
  58036. };
  58037. /**
  58038. * Helper function to add a mesh and its descendants to the list of shadow casters.
  58039. * @param mesh Mesh to add
  58040. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  58041. * @returns the Shadow Generator itself
  58042. */
  58043. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  58044. if (includeDescendants === void 0) { includeDescendants = true; }
  58045. if (!this._shadowMap) {
  58046. return this;
  58047. }
  58048. if (!this._shadowMap.renderList) {
  58049. this._shadowMap.renderList = [];
  58050. }
  58051. this._shadowMap.renderList.push(mesh);
  58052. if (includeDescendants) {
  58053. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  58054. }
  58055. return this;
  58056. var _a;
  58057. };
  58058. /**
  58059. * Helper function to remove a mesh and its descendants from the list of shadow casters
  58060. * @param mesh Mesh to remove
  58061. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  58062. * @returns the Shadow Generator itself
  58063. */
  58064. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  58065. if (includeDescendants === void 0) { includeDescendants = true; }
  58066. if (!this._shadowMap || !this._shadowMap.renderList) {
  58067. return this;
  58068. }
  58069. var index = this._shadowMap.renderList.indexOf(mesh);
  58070. if (index !== -1) {
  58071. this._shadowMap.renderList.splice(index, 1);
  58072. }
  58073. if (includeDescendants) {
  58074. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  58075. var child = _a[_i];
  58076. this.removeShadowCaster(child);
  58077. }
  58078. }
  58079. return this;
  58080. };
  58081. /**
  58082. * Returns the associated light object.
  58083. * @returns the light generating the shadow
  58084. */
  58085. ShadowGenerator.prototype.getLight = function () {
  58086. return this._light;
  58087. };
  58088. ShadowGenerator.prototype._initializeGenerator = function () {
  58089. this._light._markMeshesAsLightDirty();
  58090. this._initializeShadowMap();
  58091. };
  58092. ShadowGenerator.prototype._initializeShadowMap = function () {
  58093. var _this = this;
  58094. // Render target
  58095. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  58096. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58097. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58098. this._shadowMap.anisotropicFilteringLevel = 1;
  58099. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58100. this._shadowMap.renderParticles = false;
  58101. this._shadowMap.ignoreCameraViewport = true;
  58102. // Record Face Index before render.
  58103. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  58104. _this._currentFaceIndex = faceIndex;
  58105. });
  58106. // Custom render function.
  58107. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  58108. // Blur if required afer render.
  58109. this._shadowMap.onAfterUnbindObservable.add(function () {
  58110. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  58111. return;
  58112. }
  58113. var shadowMap = _this.getShadowMapForRendering();
  58114. if (shadowMap) {
  58115. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  58116. }
  58117. });
  58118. // Clear according to the chosen filter.
  58119. this._shadowMap.onClearObservable.add(function (engine) {
  58120. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  58121. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  58122. }
  58123. else {
  58124. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  58125. }
  58126. });
  58127. };
  58128. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  58129. var _this = this;
  58130. var engine = this._scene.getEngine();
  58131. var targetSize = this._mapSize / this.blurScale;
  58132. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  58133. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  58134. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58135. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58136. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58137. }
  58138. if (this.useKernelBlur) {
  58139. 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);
  58140. this._kernelBlurXPostprocess.width = targetSize;
  58141. this._kernelBlurXPostprocess.height = targetSize;
  58142. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  58143. effect.setTexture("textureSampler", _this._shadowMap);
  58144. });
  58145. 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);
  58146. this._kernelBlurXPostprocess.autoClear = false;
  58147. this._kernelBlurYPostprocess.autoClear = false;
  58148. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58149. this._kernelBlurXPostprocess.packedFloat = true;
  58150. this._kernelBlurYPostprocess.packedFloat = true;
  58151. }
  58152. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  58153. }
  58154. else {
  58155. 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);
  58156. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  58157. effect.setFloat2("screenSize", targetSize, targetSize);
  58158. effect.setTexture("textureSampler", _this._shadowMap);
  58159. });
  58160. this._boxBlurPostprocess.autoClear = false;
  58161. this._blurPostProcesses = [this._boxBlurPostprocess];
  58162. }
  58163. };
  58164. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  58165. var index;
  58166. var engine = this._scene.getEngine();
  58167. if (depthOnlySubMeshes.length) {
  58168. engine.setColorWrite(false);
  58169. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  58170. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  58171. }
  58172. engine.setColorWrite(true);
  58173. }
  58174. for (index = 0; index < opaqueSubMeshes.length; index++) {
  58175. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  58176. }
  58177. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  58178. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  58179. }
  58180. if (this._transparencyShadow) {
  58181. for (index = 0; index < transparentSubMeshes.length; index++) {
  58182. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  58183. }
  58184. }
  58185. };
  58186. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  58187. var _this = this;
  58188. var mesh = subMesh.getRenderingMesh();
  58189. var scene = this._scene;
  58190. var engine = scene.getEngine();
  58191. var material = subMesh.getMaterial();
  58192. if (!material) {
  58193. return;
  58194. }
  58195. // Culling
  58196. engine.setState(material.backFaceCulling);
  58197. // Managing instances
  58198. var batch = mesh._getInstancesRenderList(subMesh._id);
  58199. if (batch.mustReturn) {
  58200. return;
  58201. }
  58202. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  58203. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  58204. engine.enableEffect(this._effect);
  58205. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  58206. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  58207. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  58208. this._effect.setVector3("lightPosition", this.getLight().position);
  58209. if (scene.activeCamera) {
  58210. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  58211. }
  58212. // Alpha test
  58213. if (material && material.needAlphaTesting()) {
  58214. var alphaTexture = material.getAlphaTestTexture();
  58215. if (alphaTexture) {
  58216. this._effect.setTexture("diffuseSampler", alphaTexture);
  58217. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  58218. }
  58219. }
  58220. // Bones
  58221. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58222. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  58223. }
  58224. if (this.forceBackFacesOnly) {
  58225. engine.setState(true, 0, false, true);
  58226. }
  58227. // Draw
  58228. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  58229. if (this.forceBackFacesOnly) {
  58230. engine.setState(true, 0, false, false);
  58231. }
  58232. }
  58233. else {
  58234. // Need to reset refresh rate of the shadowMap
  58235. if (this._shadowMap) {
  58236. this._shadowMap.resetRefreshCounter();
  58237. }
  58238. }
  58239. };
  58240. ShadowGenerator.prototype._applyFilterValues = function () {
  58241. if (!this._shadowMap) {
  58242. return;
  58243. }
  58244. if (this.filter === ShadowGenerator.FILTER_NONE) {
  58245. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  58246. }
  58247. else {
  58248. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58249. }
  58250. };
  58251. /**
  58252. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  58253. * @param onCompiled Callback triggered at the and of the effects compilation
  58254. * @param options Sets of optional options forcing the compilation with different modes
  58255. */
  58256. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  58257. var _this = this;
  58258. var localOptions = __assign({ useInstances: false }, options);
  58259. var shadowMap = this.getShadowMap();
  58260. if (!shadowMap) {
  58261. if (onCompiled) {
  58262. onCompiled(this);
  58263. }
  58264. return;
  58265. }
  58266. var renderList = shadowMap.renderList;
  58267. if (!renderList) {
  58268. if (onCompiled) {
  58269. onCompiled(this);
  58270. }
  58271. return;
  58272. }
  58273. var subMeshes = new Array();
  58274. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  58275. var mesh = renderList_1[_i];
  58276. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  58277. }
  58278. if (subMeshes.length === 0) {
  58279. if (onCompiled) {
  58280. onCompiled(this);
  58281. }
  58282. return;
  58283. }
  58284. var currentIndex = 0;
  58285. var checkReady = function () {
  58286. if (!_this._scene || !_this._scene.getEngine()) {
  58287. return;
  58288. }
  58289. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  58290. currentIndex++;
  58291. if (currentIndex >= subMeshes.length) {
  58292. if (onCompiled) {
  58293. onCompiled(_this);
  58294. }
  58295. return;
  58296. }
  58297. }
  58298. setTimeout(checkReady, 16);
  58299. };
  58300. checkReady();
  58301. };
  58302. /**
  58303. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  58304. * @param subMesh The submesh we want to render in the shadow map
  58305. * @param useInstances Defines wether will draw in the map using instances
  58306. * @returns true if ready otherwise, false
  58307. */
  58308. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  58309. var defines = [];
  58310. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58311. defines.push("#define FLOAT");
  58312. }
  58313. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  58314. defines.push("#define ESM");
  58315. }
  58316. var attribs = [BABYLON.VertexBuffer.PositionKind];
  58317. var mesh = subMesh.getMesh();
  58318. var material = subMesh.getMaterial();
  58319. // Alpha test
  58320. if (material && material.needAlphaTesting()) {
  58321. var alphaTexture = material.getAlphaTestTexture();
  58322. if (alphaTexture) {
  58323. defines.push("#define ALPHATEST");
  58324. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58325. attribs.push(BABYLON.VertexBuffer.UVKind);
  58326. defines.push("#define UV1");
  58327. }
  58328. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  58329. if (alphaTexture.coordinatesIndex === 1) {
  58330. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  58331. defines.push("#define UV2");
  58332. }
  58333. }
  58334. }
  58335. }
  58336. // Bones
  58337. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58338. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58339. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58340. if (mesh.numBoneInfluencers > 4) {
  58341. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58342. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58343. }
  58344. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58345. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58346. }
  58347. else {
  58348. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58349. }
  58350. // Instances
  58351. if (useInstances) {
  58352. defines.push("#define INSTANCES");
  58353. attribs.push("world0");
  58354. attribs.push("world1");
  58355. attribs.push("world2");
  58356. attribs.push("world3");
  58357. }
  58358. // Get correct effect
  58359. var join = defines.join("\n");
  58360. if (this._cachedDefines !== join) {
  58361. this._cachedDefines = join;
  58362. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  58363. }
  58364. if (!this._effect.isReady()) {
  58365. return false;
  58366. }
  58367. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  58368. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  58369. this._initializeBlurRTTAndPostProcesses();
  58370. }
  58371. }
  58372. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  58373. return false;
  58374. }
  58375. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  58376. return false;
  58377. }
  58378. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  58379. return false;
  58380. }
  58381. return true;
  58382. };
  58383. /**
  58384. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  58385. * @param defines Defines of the material we want to update
  58386. * @param lightIndex Index of the light in the enabled light list of the material
  58387. */
  58388. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  58389. var scene = this._scene;
  58390. var light = this._light;
  58391. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  58392. return;
  58393. }
  58394. defines["SHADOW" + lightIndex] = true;
  58395. if (this.usePoissonSampling) {
  58396. defines["SHADOWPCF" + lightIndex] = true;
  58397. }
  58398. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  58399. defines["SHADOWESM" + lightIndex] = true;
  58400. }
  58401. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  58402. defines["SHADOWCLOSEESM" + lightIndex] = true;
  58403. }
  58404. if (light.needCube()) {
  58405. defines["SHADOWCUBE" + lightIndex] = true;
  58406. }
  58407. };
  58408. /**
  58409. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  58410. * defined in the generator but impacting the effect).
  58411. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  58412. * @param effect The effect we are binfing the information for
  58413. */
  58414. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  58415. var light = this._light;
  58416. var scene = this._scene;
  58417. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  58418. return;
  58419. }
  58420. var camera = scene.activeCamera;
  58421. if (!camera) {
  58422. return;
  58423. }
  58424. var shadowMap = this.getShadowMap();
  58425. if (!shadowMap) {
  58426. return;
  58427. }
  58428. if (!light.needCube()) {
  58429. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  58430. }
  58431. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  58432. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  58433. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  58434. };
  58435. /**
  58436. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  58437. * (eq to shadow prjection matrix * light transform matrix)
  58438. * @returns The transform matrix used to create the shadow map
  58439. */
  58440. ShadowGenerator.prototype.getTransformMatrix = function () {
  58441. var scene = this._scene;
  58442. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  58443. return this._transformMatrix;
  58444. }
  58445. this._currentRenderID = scene.getRenderId();
  58446. this._currentFaceIndexCache = this._currentFaceIndex;
  58447. var lightPosition = this._light.position;
  58448. if (this._light.computeTransformedInformation()) {
  58449. lightPosition = this._light.transformedPosition;
  58450. }
  58451. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  58452. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  58453. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  58454. }
  58455. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  58456. this._cachedPosition = lightPosition.clone();
  58457. this._cachedDirection = this._lightDirection.clone();
  58458. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  58459. var shadowMap = this.getShadowMap();
  58460. if (shadowMap) {
  58461. var renderList = shadowMap.renderList;
  58462. if (renderList) {
  58463. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  58464. }
  58465. }
  58466. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  58467. }
  58468. return this._transformMatrix;
  58469. };
  58470. /**
  58471. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  58472. * Cube and 2D textures for instance.
  58473. */
  58474. ShadowGenerator.prototype.recreateShadowMap = function () {
  58475. var shadowMap = this._shadowMap;
  58476. if (!shadowMap) {
  58477. return;
  58478. }
  58479. // Track render list.
  58480. var renderList = shadowMap.renderList;
  58481. // Clean up existing data.
  58482. this._disposeRTTandPostProcesses();
  58483. // Reinitializes.
  58484. this._initializeGenerator();
  58485. // Reaffect the filter to ensure a correct fallback if necessary.
  58486. this.filter = this.filter;
  58487. // Reaffect the filter.
  58488. this._applyFilterValues();
  58489. // Reaffect Render List.
  58490. this._shadowMap.renderList = renderList;
  58491. };
  58492. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  58493. if (this._shadowMap2) {
  58494. this._shadowMap2.dispose();
  58495. this._shadowMap2 = null;
  58496. }
  58497. if (this._boxBlurPostprocess) {
  58498. this._boxBlurPostprocess.dispose();
  58499. this._boxBlurPostprocess = null;
  58500. }
  58501. if (this._kernelBlurXPostprocess) {
  58502. this._kernelBlurXPostprocess.dispose();
  58503. this._kernelBlurXPostprocess = null;
  58504. }
  58505. if (this._kernelBlurYPostprocess) {
  58506. this._kernelBlurYPostprocess.dispose();
  58507. this._kernelBlurYPostprocess = null;
  58508. }
  58509. this._blurPostProcesses = [];
  58510. };
  58511. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  58512. if (this._shadowMap) {
  58513. this._shadowMap.dispose();
  58514. this._shadowMap = null;
  58515. }
  58516. this._disposeBlurPostProcesses();
  58517. };
  58518. /**
  58519. * Disposes the ShadowGenerator.
  58520. * Returns nothing.
  58521. */
  58522. ShadowGenerator.prototype.dispose = function () {
  58523. this._disposeRTTandPostProcesses();
  58524. if (this._light) {
  58525. this._light._shadowGenerator = null;
  58526. this._light._markMeshesAsLightDirty();
  58527. }
  58528. };
  58529. /**
  58530. * Serializes the shadow generator setup to a json object.
  58531. * @returns The serialized JSON object
  58532. */
  58533. ShadowGenerator.prototype.serialize = function () {
  58534. var serializationObject = {};
  58535. var shadowMap = this.getShadowMap();
  58536. if (!shadowMap) {
  58537. return serializationObject;
  58538. }
  58539. serializationObject.lightId = this._light.id;
  58540. serializationObject.mapSize = shadowMap.getRenderSize();
  58541. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  58542. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  58543. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  58544. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  58545. serializationObject.usePoissonSampling = this.usePoissonSampling;
  58546. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  58547. serializationObject.depthScale = this.depthScale;
  58548. serializationObject.darkness = this.getDarkness();
  58549. serializationObject.blurBoxOffset = this.blurBoxOffset;
  58550. serializationObject.blurKernel = this.blurKernel;
  58551. serializationObject.blurScale = this.blurScale;
  58552. serializationObject.useKernelBlur = this.useKernelBlur;
  58553. serializationObject.transparencyShadow = this._transparencyShadow;
  58554. serializationObject.renderList = [];
  58555. if (shadowMap.renderList) {
  58556. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  58557. var mesh = shadowMap.renderList[meshIndex];
  58558. serializationObject.renderList.push(mesh.id);
  58559. }
  58560. }
  58561. return serializationObject;
  58562. };
  58563. /**
  58564. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  58565. * @param parsedShadowGenerator The JSON object to parse
  58566. * @param scene The scene to create the shadow map for
  58567. * @returns The parsed shadow generator
  58568. */
  58569. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  58570. //casting to point light, as light is missing the position attr and typescript complains.
  58571. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  58572. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  58573. var shadowMap = shadowGenerator.getShadowMap();
  58574. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  58575. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  58576. meshes.forEach(function (mesh) {
  58577. if (!shadowMap) {
  58578. return;
  58579. }
  58580. if (!shadowMap.renderList) {
  58581. shadowMap.renderList = [];
  58582. }
  58583. shadowMap.renderList.push(mesh);
  58584. });
  58585. }
  58586. if (parsedShadowGenerator.usePoissonSampling) {
  58587. shadowGenerator.usePoissonSampling = true;
  58588. }
  58589. else if (parsedShadowGenerator.useExponentialShadowMap) {
  58590. shadowGenerator.useExponentialShadowMap = true;
  58591. }
  58592. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  58593. shadowGenerator.useBlurExponentialShadowMap = true;
  58594. }
  58595. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  58596. shadowGenerator.useCloseExponentialShadowMap = true;
  58597. }
  58598. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  58599. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  58600. }
  58601. else if (parsedShadowGenerator.useVarianceShadowMap) {
  58602. shadowGenerator.useExponentialShadowMap = true;
  58603. }
  58604. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  58605. shadowGenerator.useBlurExponentialShadowMap = true;
  58606. }
  58607. if (parsedShadowGenerator.depthScale) {
  58608. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  58609. }
  58610. if (parsedShadowGenerator.blurScale) {
  58611. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  58612. }
  58613. if (parsedShadowGenerator.blurBoxOffset) {
  58614. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  58615. }
  58616. if (parsedShadowGenerator.useKernelBlur) {
  58617. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  58618. }
  58619. if (parsedShadowGenerator.blurKernel) {
  58620. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  58621. }
  58622. if (parsedShadowGenerator.bias !== undefined) {
  58623. shadowGenerator.bias = parsedShadowGenerator.bias;
  58624. }
  58625. if (parsedShadowGenerator.darkness) {
  58626. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  58627. }
  58628. if (parsedShadowGenerator.transparencyShadow) {
  58629. shadowGenerator.setTransparencyShadow(true);
  58630. }
  58631. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  58632. return shadowGenerator;
  58633. };
  58634. ShadowGenerator._FILTER_NONE = 0;
  58635. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  58636. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  58637. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  58638. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  58639. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  58640. return ShadowGenerator;
  58641. }());
  58642. BABYLON.ShadowGenerator = ShadowGenerator;
  58643. })(BABYLON || (BABYLON = {}));
  58644. //# sourceMappingURL=babylon.shadowGenerator.js.map
  58645. var BABYLON;
  58646. (function (BABYLON) {
  58647. var DefaultLoadingScreen = /** @class */ (function () {
  58648. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  58649. if (_loadingText === void 0) { _loadingText = ""; }
  58650. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  58651. var _this = this;
  58652. this._renderingCanvas = _renderingCanvas;
  58653. this._loadingText = _loadingText;
  58654. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  58655. // Resize
  58656. this._resizeLoadingUI = function () {
  58657. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  58658. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  58659. if (!_this._loadingDiv) {
  58660. return;
  58661. }
  58662. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  58663. _this._loadingDiv.style.left = canvasRect.left + "px";
  58664. _this._loadingDiv.style.top = canvasRect.top + "px";
  58665. _this._loadingDiv.style.width = canvasRect.width + "px";
  58666. _this._loadingDiv.style.height = canvasRect.height + "px";
  58667. };
  58668. }
  58669. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  58670. if (this._loadingDiv) {
  58671. // Do not add a loading screen if there is already one
  58672. return;
  58673. }
  58674. this._loadingDiv = document.createElement("div");
  58675. this._loadingDiv.id = "babylonjsLoadingDiv";
  58676. this._loadingDiv.style.opacity = "0";
  58677. this._loadingDiv.style.transition = "opacity 1.5s ease";
  58678. this._loadingDiv.style.pointerEvents = "none";
  58679. // Loading text
  58680. this._loadingTextDiv = document.createElement("div");
  58681. this._loadingTextDiv.style.position = "absolute";
  58682. this._loadingTextDiv.style.left = "0";
  58683. this._loadingTextDiv.style.top = "50%";
  58684. this._loadingTextDiv.style.marginTop = "80px";
  58685. this._loadingTextDiv.style.width = "100%";
  58686. this._loadingTextDiv.style.height = "20px";
  58687. this._loadingTextDiv.style.fontFamily = "Arial";
  58688. this._loadingTextDiv.style.fontSize = "14px";
  58689. this._loadingTextDiv.style.color = "white";
  58690. this._loadingTextDiv.style.textAlign = "center";
  58691. this._loadingTextDiv.innerHTML = "Loading";
  58692. this._loadingDiv.appendChild(this._loadingTextDiv);
  58693. //set the predefined text
  58694. this._loadingTextDiv.innerHTML = this._loadingText;
  58695. // Generating keyframes
  58696. var style = document.createElement('style');
  58697. style.type = 'text/css';
  58698. 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 }";
  58699. style.innerHTML = keyFrames;
  58700. document.getElementsByTagName('head')[0].appendChild(style);
  58701. // Loading img
  58702. var imgBack = new Image();
  58703. 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";
  58704. imgBack.style.position = "absolute";
  58705. imgBack.style.left = "50%";
  58706. imgBack.style.top = "50%";
  58707. imgBack.style.marginLeft = "-60px";
  58708. imgBack.style.marginTop = "-60px";
  58709. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  58710. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  58711. imgBack.style.transformOrigin = "50% 50%";
  58712. imgBack.style.webkitTransformOrigin = "50% 50%";
  58713. this._loadingDiv.appendChild(imgBack);
  58714. this._resizeLoadingUI();
  58715. window.addEventListener("resize", this._resizeLoadingUI);
  58716. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  58717. document.body.appendChild(this._loadingDiv);
  58718. this._loadingDiv.style.opacity = "1";
  58719. };
  58720. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  58721. var _this = this;
  58722. if (!this._loadingDiv) {
  58723. return;
  58724. }
  58725. var onTransitionEnd = function () {
  58726. if (!_this._loadingDiv) {
  58727. return;
  58728. }
  58729. document.body.removeChild(_this._loadingDiv);
  58730. window.removeEventListener("resize", _this._resizeLoadingUI);
  58731. _this._loadingDiv = null;
  58732. };
  58733. this._loadingDiv.style.opacity = "0";
  58734. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  58735. };
  58736. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  58737. set: function (text) {
  58738. this._loadingText = text;
  58739. if (this._loadingTextDiv) {
  58740. this._loadingTextDiv.innerHTML = this._loadingText;
  58741. }
  58742. },
  58743. enumerable: true,
  58744. configurable: true
  58745. });
  58746. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  58747. get: function () {
  58748. return this._loadingDivBackgroundColor;
  58749. },
  58750. set: function (color) {
  58751. this._loadingDivBackgroundColor = color;
  58752. if (!this._loadingDiv) {
  58753. return;
  58754. }
  58755. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  58756. },
  58757. enumerable: true,
  58758. configurable: true
  58759. });
  58760. return DefaultLoadingScreen;
  58761. }());
  58762. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  58763. })(BABYLON || (BABYLON = {}));
  58764. //# sourceMappingURL=babylon.loadingScreen.js.map
  58765. var BABYLON;
  58766. (function (BABYLON) {
  58767. var SceneLoaderProgressEvent = /** @class */ (function () {
  58768. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  58769. this.lengthComputable = lengthComputable;
  58770. this.loaded = loaded;
  58771. this.total = total;
  58772. }
  58773. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  58774. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  58775. };
  58776. return SceneLoaderProgressEvent;
  58777. }());
  58778. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  58779. var SceneLoader = /** @class */ (function () {
  58780. function SceneLoader() {
  58781. }
  58782. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  58783. get: function () {
  58784. return 0;
  58785. },
  58786. enumerable: true,
  58787. configurable: true
  58788. });
  58789. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  58790. get: function () {
  58791. return 1;
  58792. },
  58793. enumerable: true,
  58794. configurable: true
  58795. });
  58796. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  58797. get: function () {
  58798. return 2;
  58799. },
  58800. enumerable: true,
  58801. configurable: true
  58802. });
  58803. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  58804. get: function () {
  58805. return 3;
  58806. },
  58807. enumerable: true,
  58808. configurable: true
  58809. });
  58810. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  58811. get: function () {
  58812. return SceneLoader._ForceFullSceneLoadingForIncremental;
  58813. },
  58814. set: function (value) {
  58815. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  58816. },
  58817. enumerable: true,
  58818. configurable: true
  58819. });
  58820. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  58821. get: function () {
  58822. return SceneLoader._ShowLoadingScreen;
  58823. },
  58824. set: function (value) {
  58825. SceneLoader._ShowLoadingScreen = value;
  58826. },
  58827. enumerable: true,
  58828. configurable: true
  58829. });
  58830. Object.defineProperty(SceneLoader, "loggingLevel", {
  58831. get: function () {
  58832. return SceneLoader._loggingLevel;
  58833. },
  58834. set: function (value) {
  58835. SceneLoader._loggingLevel = value;
  58836. },
  58837. enumerable: true,
  58838. configurable: true
  58839. });
  58840. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  58841. get: function () {
  58842. return SceneLoader._CleanBoneMatrixWeights;
  58843. },
  58844. set: function (value) {
  58845. SceneLoader._CleanBoneMatrixWeights = value;
  58846. },
  58847. enumerable: true,
  58848. configurable: true
  58849. });
  58850. SceneLoader._getDefaultPlugin = function () {
  58851. return SceneLoader._registeredPlugins[".babylon"];
  58852. };
  58853. SceneLoader._getPluginForExtension = function (extension) {
  58854. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  58855. if (registeredPlugin) {
  58856. return registeredPlugin;
  58857. }
  58858. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  58859. return SceneLoader._getDefaultPlugin();
  58860. };
  58861. SceneLoader._getPluginForDirectLoad = function (data) {
  58862. for (var extension in SceneLoader._registeredPlugins) {
  58863. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  58864. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  58865. return SceneLoader._registeredPlugins[extension];
  58866. }
  58867. }
  58868. return SceneLoader._getDefaultPlugin();
  58869. };
  58870. SceneLoader._getPluginForFilename = function (sceneFilename) {
  58871. if (sceneFilename.name) {
  58872. sceneFilename = sceneFilename.name;
  58873. }
  58874. var queryStringPosition = sceneFilename.indexOf("?");
  58875. if (queryStringPosition !== -1) {
  58876. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  58877. }
  58878. var dotPosition = sceneFilename.lastIndexOf(".");
  58879. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  58880. return SceneLoader._getPluginForExtension(extension);
  58881. };
  58882. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  58883. SceneLoader._getDirectLoad = function (sceneFilename) {
  58884. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  58885. return sceneFilename.substr(5);
  58886. }
  58887. return null;
  58888. };
  58889. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  58890. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  58891. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  58892. var plugin;
  58893. if (registeredPlugin.plugin.createPlugin) {
  58894. plugin = registeredPlugin.plugin.createPlugin();
  58895. }
  58896. else {
  58897. plugin = registeredPlugin.plugin;
  58898. }
  58899. var useArrayBuffer = registeredPlugin.isBinary;
  58900. var database;
  58901. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  58902. var dataCallback = function (data, responseURL) {
  58903. if (scene.isDisposed) {
  58904. onError("Scene has been disposed");
  58905. return;
  58906. }
  58907. scene.database = database;
  58908. onSuccess(plugin, data, responseURL);
  58909. };
  58910. var request = null;
  58911. var pluginDisposed = false;
  58912. var onDisposeObservable = plugin.onDisposeObservable;
  58913. if (onDisposeObservable) {
  58914. onDisposeObservable.add(function () {
  58915. pluginDisposed = true;
  58916. if (request) {
  58917. request.abort();
  58918. request = null;
  58919. }
  58920. onDispose();
  58921. });
  58922. }
  58923. var manifestChecked = function () {
  58924. if (pluginDisposed) {
  58925. return;
  58926. }
  58927. var url = rootUrl + sceneFilename;
  58928. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  58929. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  58930. } : undefined, database, useArrayBuffer, function (request, exception) {
  58931. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  58932. });
  58933. };
  58934. if (directLoad) {
  58935. dataCallback(directLoad);
  58936. return plugin;
  58937. }
  58938. if (rootUrl.indexOf("file:") === -1) {
  58939. if (scene.getEngine().enableOfflineSupport) {
  58940. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  58941. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  58942. }
  58943. else {
  58944. manifestChecked();
  58945. }
  58946. }
  58947. else {
  58948. var fileOrString = sceneFilename;
  58949. if (fileOrString.name) {
  58950. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  58951. }
  58952. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  58953. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  58954. }
  58955. else {
  58956. onError("Unable to find file named " + sceneFilename);
  58957. }
  58958. }
  58959. return plugin;
  58960. };
  58961. // Public functions
  58962. SceneLoader.GetPluginForExtension = function (extension) {
  58963. return SceneLoader._getPluginForExtension(extension).plugin;
  58964. };
  58965. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  58966. return !!SceneLoader._registeredPlugins[extension];
  58967. };
  58968. SceneLoader.RegisterPlugin = function (plugin) {
  58969. if (typeof plugin.extensions === "string") {
  58970. var extension = plugin.extensions;
  58971. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  58972. plugin: plugin,
  58973. isBinary: false
  58974. };
  58975. }
  58976. else {
  58977. var extensions = plugin.extensions;
  58978. Object.keys(extensions).forEach(function (extension) {
  58979. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  58980. plugin: plugin,
  58981. isBinary: extensions[extension].isBinary
  58982. };
  58983. });
  58984. }
  58985. };
  58986. /**
  58987. * Import meshes into a scene
  58988. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  58989. * @param rootUrl a string that defines the root url for scene and resources
  58990. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  58991. * @param scene the instance of BABYLON.Scene to append to
  58992. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  58993. * @param onProgress a callback with a progress event for each file being loaded
  58994. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  58995. */
  58996. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  58997. if (onSuccess === void 0) { onSuccess = null; }
  58998. if (onProgress === void 0) { onProgress = null; }
  58999. if (onError === void 0) { onError = null; }
  59000. if (pluginExtension === void 0) { pluginExtension = null; }
  59001. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59002. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59003. return null;
  59004. }
  59005. var loadingToken = {};
  59006. scene._addPendingData(loadingToken);
  59007. var disposeHandler = function () {
  59008. scene._removePendingData(loadingToken);
  59009. };
  59010. var errorHandler = function (message, exception) {
  59011. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  59012. if (onError) {
  59013. onError(scene, errorMessage, exception);
  59014. }
  59015. else {
  59016. BABYLON.Tools.Error(errorMessage);
  59017. // should the exception be thrown?
  59018. }
  59019. disposeHandler();
  59020. };
  59021. var progressHandler = onProgress ? function (event) {
  59022. try {
  59023. onProgress(event);
  59024. }
  59025. catch (e) {
  59026. errorHandler("Error in onProgress callback", e);
  59027. }
  59028. } : undefined;
  59029. var successHandler = function (meshes, particleSystems, skeletons) {
  59030. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  59031. if (onSuccess) {
  59032. try {
  59033. onSuccess(meshes, particleSystems, skeletons);
  59034. }
  59035. catch (e) {
  59036. errorHandler("Error in onSuccess callback", e);
  59037. }
  59038. }
  59039. scene._removePendingData(loadingToken);
  59040. };
  59041. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59042. if (plugin.rewriteRootURL) {
  59043. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  59044. }
  59045. if (sceneFilename === "") {
  59046. if (sceneFilename === "") {
  59047. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  59048. }
  59049. }
  59050. if (plugin.importMesh) {
  59051. var syncedPlugin = plugin;
  59052. var meshes = new Array();
  59053. var particleSystems = new Array();
  59054. var skeletons = new Array();
  59055. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  59056. return;
  59057. }
  59058. scene.loadingPluginName = plugin.name;
  59059. successHandler(meshes, particleSystems, skeletons);
  59060. }
  59061. else {
  59062. var asyncedPlugin = plugin;
  59063. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  59064. scene.loadingPluginName = plugin.name;
  59065. successHandler(meshes, particleSystems, skeletons);
  59066. }, progressHandler, errorHandler);
  59067. }
  59068. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59069. };
  59070. /**
  59071. * Load a scene
  59072. * @param rootUrl a string that defines the root url for scene and resources
  59073. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59074. * @param engine is the instance of BABYLON.Engine to use to create the scene
  59075. * @param onSuccess a callback with the scene when import succeeds
  59076. * @param onProgress a callback with a progress event for each file being loaded
  59077. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59078. */
  59079. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  59080. if (onSuccess === void 0) { onSuccess = null; }
  59081. if (onProgress === void 0) { onProgress = null; }
  59082. if (onError === void 0) { onError = null; }
  59083. if (pluginExtension === void 0) { pluginExtension = null; }
  59084. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  59085. };
  59086. /**
  59087. * Append a scene
  59088. * @param rootUrl a string that defines the root url for scene and resources
  59089. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59090. * @param scene is the instance of BABYLON.Scene to append to
  59091. * @param onSuccess a callback with the scene when import succeeds
  59092. * @param onProgress a callback with a progress event for each file being loaded
  59093. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59094. */
  59095. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59096. if (onSuccess === void 0) { onSuccess = null; }
  59097. if (onProgress === void 0) { onProgress = null; }
  59098. if (onError === void 0) { onError = null; }
  59099. if (pluginExtension === void 0) { pluginExtension = null; }
  59100. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59101. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59102. return null;
  59103. }
  59104. if (SceneLoader.ShowLoadingScreen) {
  59105. scene.getEngine().displayLoadingUI();
  59106. }
  59107. var loadingToken = {};
  59108. scene._addPendingData(loadingToken);
  59109. var disposeHandler = function () {
  59110. scene._removePendingData(loadingToken);
  59111. scene.getEngine().hideLoadingUI();
  59112. };
  59113. var errorHandler = function (message, exception) {
  59114. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  59115. if (onError) {
  59116. onError(scene, errorMessage, exception);
  59117. }
  59118. else {
  59119. BABYLON.Tools.Error(errorMessage);
  59120. // should the exception be thrown?
  59121. }
  59122. disposeHandler();
  59123. };
  59124. var progressHandler = onProgress ? function (event) {
  59125. try {
  59126. onProgress(event);
  59127. }
  59128. catch (e) {
  59129. errorHandler("Error in onProgress callback", e);
  59130. }
  59131. } : undefined;
  59132. var successHandler = function () {
  59133. if (onSuccess) {
  59134. try {
  59135. onSuccess(scene);
  59136. }
  59137. catch (e) {
  59138. errorHandler("Error in onSuccess callback", e);
  59139. }
  59140. }
  59141. scene._removePendingData(loadingToken);
  59142. };
  59143. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59144. if (sceneFilename === "") {
  59145. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  59146. }
  59147. if (plugin.load) {
  59148. var syncedPlugin = plugin;
  59149. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  59150. return;
  59151. }
  59152. scene.loadingPluginName = plugin.name;
  59153. successHandler();
  59154. }
  59155. else {
  59156. var asyncedPlugin = plugin;
  59157. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  59158. scene.loadingPluginName = plugin.name;
  59159. successHandler();
  59160. }, progressHandler, errorHandler);
  59161. }
  59162. if (SceneLoader.ShowLoadingScreen) {
  59163. scene.executeWhenReady(function () {
  59164. scene.getEngine().hideLoadingUI();
  59165. });
  59166. }
  59167. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59168. };
  59169. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59170. if (onSuccess === void 0) { onSuccess = null; }
  59171. if (onProgress === void 0) { onProgress = null; }
  59172. if (onError === void 0) { onError = null; }
  59173. if (pluginExtension === void 0) { pluginExtension = null; }
  59174. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59175. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59176. return null;
  59177. }
  59178. var loadingToken = {};
  59179. scene._addPendingData(loadingToken);
  59180. var disposeHandler = function () {
  59181. scene._removePendingData(loadingToken);
  59182. };
  59183. var errorHandler = function (message, exception) {
  59184. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  59185. if (onError) {
  59186. onError(scene, errorMessage, exception);
  59187. }
  59188. else {
  59189. BABYLON.Tools.Error(errorMessage);
  59190. // should the exception be thrown?
  59191. }
  59192. disposeHandler();
  59193. };
  59194. var progressHandler = onProgress ? function (event) {
  59195. try {
  59196. onProgress(event);
  59197. }
  59198. catch (e) {
  59199. errorHandler("Error in onProgress callback", e);
  59200. }
  59201. } : undefined;
  59202. var successHandler = function (assets) {
  59203. if (onSuccess) {
  59204. try {
  59205. onSuccess(assets);
  59206. }
  59207. catch (e) {
  59208. errorHandler("Error in onSuccess callback", e);
  59209. }
  59210. }
  59211. scene._removePendingData(loadingToken);
  59212. };
  59213. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59214. if (plugin.loadAssets) {
  59215. var syncedPlugin = plugin;
  59216. var assetContainer = syncedPlugin.loadAssets(scene, data, rootUrl, errorHandler);
  59217. if (!assetContainer) {
  59218. return;
  59219. }
  59220. scene.loadingPluginName = plugin.name;
  59221. successHandler(assetContainer);
  59222. }
  59223. else if (plugin.loadAssetsAsync) {
  59224. var asyncedPlugin = plugin;
  59225. asyncedPlugin.loadAssetsAsync(scene, data, rootUrl, function (assetContainer) {
  59226. if (assetContainer) {
  59227. scene.loadingPluginName = plugin.name;
  59228. successHandler(assetContainer);
  59229. }
  59230. }, progressHandler, errorHandler);
  59231. }
  59232. else {
  59233. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssets or loadAssetsAsync method.");
  59234. }
  59235. if (SceneLoader.ShowLoadingScreen) {
  59236. scene.executeWhenReady(function () {
  59237. scene.getEngine().hideLoadingUI();
  59238. });
  59239. }
  59240. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59241. };
  59242. // Flags
  59243. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  59244. SceneLoader._ShowLoadingScreen = true;
  59245. SceneLoader._CleanBoneMatrixWeights = false;
  59246. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  59247. // Members
  59248. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  59249. SceneLoader._registeredPlugins = {};
  59250. return SceneLoader;
  59251. }());
  59252. BABYLON.SceneLoader = SceneLoader;
  59253. ;
  59254. })(BABYLON || (BABYLON = {}));
  59255. //# sourceMappingURL=babylon.sceneLoader.js.map
  59256. var BABYLON;
  59257. (function (BABYLON) {
  59258. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  59259. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  59260. var parsedMaterial = parsedData.materials[index];
  59261. if (parsedMaterial.id === id) {
  59262. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  59263. }
  59264. }
  59265. return null;
  59266. };
  59267. var isDescendantOf = function (mesh, names, hierarchyIds) {
  59268. for (var i in names) {
  59269. if (mesh.name === names[i]) {
  59270. hierarchyIds.push(mesh.id);
  59271. return true;
  59272. }
  59273. }
  59274. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  59275. hierarchyIds.push(mesh.id);
  59276. return true;
  59277. }
  59278. return false;
  59279. };
  59280. var logOperation = function (operation, producer) {
  59281. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  59282. };
  59283. var loadAssets = function (scene, data, rootUrl, onError, addToScene) {
  59284. if (addToScene === void 0) { addToScene = false; }
  59285. var container = new BABYLON.AssetContainer(scene);
  59286. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  59287. // when SceneLoader.debugLogging = true (default), or exception encountered.
  59288. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  59289. // and avoid problems with multiple concurrent .babylon loads.
  59290. var log = "importScene has failed JSON parse";
  59291. try {
  59292. var parsedData = JSON.parse(data);
  59293. log = "";
  59294. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  59295. var index;
  59296. var cache;
  59297. // Lights
  59298. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  59299. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  59300. var parsedLight = parsedData.lights[index];
  59301. var light = BABYLON.Light.Parse(parsedLight, scene);
  59302. if (light) {
  59303. container.lights.push(light);
  59304. log += (index === 0 ? "\n\tLights:" : "");
  59305. log += "\n\t\t" + light.toString(fullDetails);
  59306. }
  59307. }
  59308. }
  59309. // Animations
  59310. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  59311. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  59312. var parsedAnimation = parsedData.animations[index];
  59313. var animation = BABYLON.Animation.Parse(parsedAnimation);
  59314. scene.animations.push(animation);
  59315. container.animations.push(animation);
  59316. log += (index === 0 ? "\n\tAnimations:" : "");
  59317. log += "\n\t\t" + animation.toString(fullDetails);
  59318. }
  59319. }
  59320. // Materials
  59321. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  59322. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  59323. var parsedMaterial = parsedData.materials[index];
  59324. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  59325. container.materials.push(mat);
  59326. log += (index === 0 ? "\n\tMaterials:" : "");
  59327. log += "\n\t\t" + mat.toString(fullDetails);
  59328. }
  59329. }
  59330. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  59331. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  59332. var parsedMultiMaterial = parsedData.multiMaterials[index];
  59333. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  59334. container.multiMaterials.push(mmat);
  59335. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  59336. log += "\n\t\t" + mmat.toString(fullDetails);
  59337. }
  59338. }
  59339. // Morph targets
  59340. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  59341. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  59342. var managerData = _a[_i];
  59343. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  59344. }
  59345. }
  59346. // Skeletons
  59347. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  59348. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  59349. var parsedSkeleton = parsedData.skeletons[index];
  59350. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  59351. container.skeletons.push(skeleton);
  59352. log += (index === 0 ? "\n\tSkeletons:" : "");
  59353. log += "\n\t\t" + skeleton.toString(fullDetails);
  59354. }
  59355. }
  59356. // Geometries
  59357. var geometries = parsedData.geometries;
  59358. if (geometries !== undefined && geometries !== null) {
  59359. var addedGeometry = new Array();
  59360. // Boxes
  59361. var boxes = geometries.boxes;
  59362. if (boxes !== undefined && boxes !== null) {
  59363. for (index = 0, cache = boxes.length; index < cache; index++) {
  59364. var parsedBox = boxes[index];
  59365. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  59366. }
  59367. }
  59368. // Spheres
  59369. var spheres = geometries.spheres;
  59370. if (spheres !== undefined && spheres !== null) {
  59371. for (index = 0, cache = spheres.length; index < cache; index++) {
  59372. var parsedSphere = spheres[index];
  59373. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  59374. }
  59375. }
  59376. // Cylinders
  59377. var cylinders = geometries.cylinders;
  59378. if (cylinders !== undefined && cylinders !== null) {
  59379. for (index = 0, cache = cylinders.length; index < cache; index++) {
  59380. var parsedCylinder = cylinders[index];
  59381. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  59382. }
  59383. }
  59384. // Toruses
  59385. var toruses = geometries.toruses;
  59386. if (toruses !== undefined && toruses !== null) {
  59387. for (index = 0, cache = toruses.length; index < cache; index++) {
  59388. var parsedTorus = toruses[index];
  59389. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  59390. }
  59391. }
  59392. // Grounds
  59393. var grounds = geometries.grounds;
  59394. if (grounds !== undefined && grounds !== null) {
  59395. for (index = 0, cache = grounds.length; index < cache; index++) {
  59396. var parsedGround = grounds[index];
  59397. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  59398. }
  59399. }
  59400. // Planes
  59401. var planes = geometries.planes;
  59402. if (planes !== undefined && planes !== null) {
  59403. for (index = 0, cache = planes.length; index < cache; index++) {
  59404. var parsedPlane = planes[index];
  59405. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  59406. }
  59407. }
  59408. // TorusKnots
  59409. var torusKnots = geometries.torusKnots;
  59410. if (torusKnots !== undefined && torusKnots !== null) {
  59411. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  59412. var parsedTorusKnot = torusKnots[index];
  59413. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  59414. }
  59415. }
  59416. // VertexData
  59417. var vertexData = geometries.vertexData;
  59418. if (vertexData !== undefined && vertexData !== null) {
  59419. for (index = 0, cache = vertexData.length; index < cache; index++) {
  59420. var parsedVertexData = vertexData[index];
  59421. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  59422. }
  59423. }
  59424. addedGeometry.forEach(function (g) {
  59425. if (g) {
  59426. container.geometries.push(g);
  59427. }
  59428. });
  59429. }
  59430. // Transform nodes
  59431. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  59432. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  59433. var parsedTransformNode = parsedData.transformNodes[index];
  59434. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  59435. container.transformNodes.push(node);
  59436. }
  59437. }
  59438. // Meshes
  59439. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  59440. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  59441. var parsedMesh = parsedData.meshes[index];
  59442. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  59443. container.meshes.push(mesh);
  59444. log += (index === 0 ? "\n\tMeshes:" : "");
  59445. log += "\n\t\t" + mesh.toString(fullDetails);
  59446. }
  59447. }
  59448. // Cameras
  59449. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  59450. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  59451. var parsedCamera = parsedData.cameras[index];
  59452. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  59453. container.cameras.push(camera);
  59454. log += (index === 0 ? "\n\tCameras:" : "");
  59455. log += "\n\t\t" + camera.toString(fullDetails);
  59456. }
  59457. }
  59458. // Browsing all the graph to connect the dots
  59459. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  59460. var camera = scene.cameras[index];
  59461. if (camera._waitingParentId) {
  59462. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  59463. camera._waitingParentId = null;
  59464. }
  59465. }
  59466. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  59467. var light_1 = scene.lights[index];
  59468. if (light_1 && light_1._waitingParentId) {
  59469. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  59470. light_1._waitingParentId = null;
  59471. }
  59472. }
  59473. // Sounds
  59474. // TODO: add sound
  59475. var loadedSounds = [];
  59476. var loadedSound;
  59477. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  59478. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  59479. var parsedSound = parsedData.sounds[index];
  59480. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  59481. if (!parsedSound.url)
  59482. parsedSound.url = parsedSound.name;
  59483. if (!loadedSounds[parsedSound.url]) {
  59484. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  59485. loadedSounds[parsedSound.url] = loadedSound;
  59486. container.sounds.push(loadedSound);
  59487. }
  59488. else {
  59489. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  59490. }
  59491. }
  59492. else {
  59493. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  59494. }
  59495. }
  59496. }
  59497. loadedSounds = [];
  59498. // Connect parents & children and parse actions
  59499. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  59500. var transformNode = scene.transformNodes[index];
  59501. if (transformNode._waitingParentId) {
  59502. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  59503. transformNode._waitingParentId = null;
  59504. }
  59505. }
  59506. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  59507. var mesh = scene.meshes[index];
  59508. if (mesh._waitingParentId) {
  59509. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  59510. mesh._waitingParentId = null;
  59511. }
  59512. if (mesh._waitingActions) {
  59513. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  59514. mesh._waitingActions = null;
  59515. }
  59516. }
  59517. // freeze world matrix application
  59518. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  59519. var currentMesh = scene.meshes[index];
  59520. if (currentMesh._waitingFreezeWorldMatrix) {
  59521. currentMesh.freezeWorldMatrix();
  59522. currentMesh._waitingFreezeWorldMatrix = null;
  59523. }
  59524. else {
  59525. currentMesh.computeWorldMatrix(true);
  59526. }
  59527. }
  59528. // Particles Systems
  59529. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  59530. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  59531. var parsedParticleSystem = parsedData.particleSystems[index];
  59532. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  59533. container.particleSystems.push(ps);
  59534. }
  59535. }
  59536. // Lens flares
  59537. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  59538. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  59539. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  59540. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  59541. container.lensFlareSystems.push(lf);
  59542. }
  59543. }
  59544. // Shadows
  59545. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  59546. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  59547. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  59548. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  59549. container.shadowGenerators.push(sg);
  59550. }
  59551. }
  59552. // Lights exclusions / inclusions
  59553. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  59554. var light_2 = scene.lights[index];
  59555. // Excluded check
  59556. if (light_2._excludedMeshesIds.length > 0) {
  59557. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  59558. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  59559. if (excludedMesh) {
  59560. light_2.excludedMeshes.push(excludedMesh);
  59561. }
  59562. }
  59563. light_2._excludedMeshesIds = [];
  59564. }
  59565. // Included check
  59566. if (light_2._includedOnlyMeshesIds.length > 0) {
  59567. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  59568. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  59569. if (includedOnlyMesh) {
  59570. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  59571. }
  59572. }
  59573. light_2._includedOnlyMeshesIds = [];
  59574. }
  59575. }
  59576. // Actions (scene)
  59577. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  59578. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  59579. }
  59580. if (!addToScene) {
  59581. container.removeAllFromScene();
  59582. }
  59583. return container;
  59584. }
  59585. catch (err) {
  59586. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  59587. if (onError) {
  59588. onError(msg, err);
  59589. }
  59590. else {
  59591. BABYLON.Tools.Log(msg);
  59592. throw err;
  59593. }
  59594. }
  59595. finally {
  59596. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  59597. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  59598. }
  59599. }
  59600. return null;
  59601. };
  59602. BABYLON.SceneLoader.RegisterPlugin({
  59603. name: "babylon.js",
  59604. extensions: ".babylon",
  59605. canDirectLoad: function (data) {
  59606. if (data.indexOf("babylon") !== -1) {
  59607. return true;
  59608. }
  59609. return false;
  59610. },
  59611. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  59612. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  59613. // when SceneLoader.debugLogging = true (default), or exception encountered.
  59614. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  59615. // and avoid problems with multiple concurrent .babylon loads.
  59616. var log = "importMesh has failed JSON parse";
  59617. try {
  59618. var parsedData = JSON.parse(data);
  59619. log = "";
  59620. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  59621. if (!meshesNames) {
  59622. meshesNames = null;
  59623. }
  59624. else if (!Array.isArray(meshesNames)) {
  59625. meshesNames = [meshesNames];
  59626. }
  59627. var hierarchyIds = new Array();
  59628. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  59629. var loadedSkeletonsIds = [];
  59630. var loadedMaterialsIds = [];
  59631. var index;
  59632. var cache;
  59633. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  59634. var parsedMesh = parsedData.meshes[index];
  59635. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  59636. if (meshesNames !== null) {
  59637. // Remove found mesh name from list.
  59638. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  59639. }
  59640. //Geometry?
  59641. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  59642. //does the file contain geometries?
  59643. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  59644. //find the correct geometry and add it to the scene
  59645. var found = false;
  59646. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  59647. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  59648. return;
  59649. }
  59650. else {
  59651. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  59652. if (parsedGeometryData.id === parsedMesh.geometryId) {
  59653. switch (geometryType) {
  59654. case "boxes":
  59655. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  59656. break;
  59657. case "spheres":
  59658. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  59659. break;
  59660. case "cylinders":
  59661. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  59662. break;
  59663. case "toruses":
  59664. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  59665. break;
  59666. case "grounds":
  59667. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  59668. break;
  59669. case "planes":
  59670. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  59671. break;
  59672. case "torusKnots":
  59673. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  59674. break;
  59675. case "vertexData":
  59676. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  59677. break;
  59678. }
  59679. found = true;
  59680. }
  59681. });
  59682. }
  59683. });
  59684. if (found === false) {
  59685. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  59686. }
  59687. }
  59688. }
  59689. // Material ?
  59690. if (parsedMesh.materialId) {
  59691. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  59692. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  59693. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  59694. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  59695. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  59696. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  59697. var subMatId = parsedMultiMaterial.materials[matIndex];
  59698. loadedMaterialsIds.push(subMatId);
  59699. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  59700. if (mat) {
  59701. log += "\n\tMaterial " + mat.toString(fullDetails);
  59702. }
  59703. }
  59704. loadedMaterialsIds.push(parsedMultiMaterial.id);
  59705. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  59706. if (mmat) {
  59707. materialFound = true;
  59708. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  59709. }
  59710. break;
  59711. }
  59712. }
  59713. }
  59714. if (materialFound === false) {
  59715. loadedMaterialsIds.push(parsedMesh.materialId);
  59716. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  59717. if (!mat) {
  59718. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  59719. }
  59720. else {
  59721. log += "\n\tMaterial " + mat.toString(fullDetails);
  59722. }
  59723. }
  59724. }
  59725. // Skeleton ?
  59726. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  59727. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  59728. if (skeletonAlreadyLoaded === false) {
  59729. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  59730. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  59731. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  59732. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  59733. skeletons.push(skeleton);
  59734. loadedSkeletonsIds.push(parsedSkeleton.id);
  59735. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  59736. }
  59737. }
  59738. }
  59739. }
  59740. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  59741. meshes.push(mesh);
  59742. log += "\n\tMesh " + mesh.toString(fullDetails);
  59743. }
  59744. }
  59745. // Connecting parents
  59746. var currentMesh;
  59747. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  59748. currentMesh = scene.meshes[index];
  59749. if (currentMesh._waitingParentId) {
  59750. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  59751. currentMesh._waitingParentId = null;
  59752. }
  59753. }
  59754. // freeze and compute world matrix application
  59755. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  59756. currentMesh = scene.meshes[index];
  59757. if (currentMesh._waitingFreezeWorldMatrix) {
  59758. currentMesh.freezeWorldMatrix();
  59759. currentMesh._waitingFreezeWorldMatrix = null;
  59760. }
  59761. else {
  59762. currentMesh.computeWorldMatrix(true);
  59763. }
  59764. }
  59765. }
  59766. // Particles
  59767. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  59768. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  59769. var parsedParticleSystem = parsedData.particleSystems[index];
  59770. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  59771. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  59772. }
  59773. }
  59774. }
  59775. return true;
  59776. }
  59777. catch (err) {
  59778. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  59779. if (onError) {
  59780. onError(msg, err);
  59781. }
  59782. else {
  59783. BABYLON.Tools.Log(msg);
  59784. throw err;
  59785. }
  59786. }
  59787. finally {
  59788. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  59789. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  59790. }
  59791. }
  59792. return false;
  59793. },
  59794. load: function (scene, data, rootUrl, onError) {
  59795. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  59796. // when SceneLoader.debugLogging = true (default), or exception encountered.
  59797. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  59798. // and avoid problems with multiple concurrent .babylon loads.
  59799. var log = "importScene has failed JSON parse";
  59800. try {
  59801. var parsedData = JSON.parse(data);
  59802. log = "";
  59803. // Scene
  59804. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  59805. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  59806. }
  59807. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  59808. scene.autoClear = parsedData.autoClear;
  59809. }
  59810. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  59811. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  59812. }
  59813. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  59814. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  59815. }
  59816. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  59817. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  59818. }
  59819. // Fog
  59820. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  59821. scene.fogMode = parsedData.fogMode;
  59822. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  59823. scene.fogStart = parsedData.fogStart;
  59824. scene.fogEnd = parsedData.fogEnd;
  59825. scene.fogDensity = parsedData.fogDensity;
  59826. log += "\tFog mode for scene: ";
  59827. switch (scene.fogMode) {
  59828. // getters not compiling, so using hardcoded
  59829. case 1:
  59830. log += "exp\n";
  59831. break;
  59832. case 2:
  59833. log += "exp2\n";
  59834. break;
  59835. case 3:
  59836. log += "linear\n";
  59837. break;
  59838. }
  59839. }
  59840. //Physics
  59841. if (parsedData.physicsEnabled) {
  59842. var physicsPlugin;
  59843. if (parsedData.physicsEngine === "cannon") {
  59844. physicsPlugin = new BABYLON.CannonJSPlugin();
  59845. }
  59846. else if (parsedData.physicsEngine === "oimo") {
  59847. physicsPlugin = new BABYLON.OimoJSPlugin();
  59848. }
  59849. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  59850. //else - default engine, which is currently oimo
  59851. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  59852. scene.enablePhysics(physicsGravity, physicsPlugin);
  59853. }
  59854. // Metadata
  59855. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  59856. scene.metadata = parsedData.metadata;
  59857. }
  59858. //collisions, if defined. otherwise, default is true
  59859. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  59860. scene.collisionsEnabled = parsedData.collisionsEnabled;
  59861. }
  59862. scene.workerCollisions = !!parsedData.workerCollisions;
  59863. var container = loadAssets(scene, data, rootUrl, onerror, true);
  59864. if (!container) {
  59865. return false;
  59866. }
  59867. if (parsedData.autoAnimate) {
  59868. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  59869. }
  59870. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  59871. scene.setActiveCameraByID(parsedData.activeCameraID);
  59872. }
  59873. // Environment texture
  59874. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  59875. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  59876. if (parsedData.createDefaultSkybox === true) {
  59877. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  59878. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  59879. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  59880. }
  59881. }
  59882. // Finish
  59883. return true;
  59884. }
  59885. catch (err) {
  59886. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  59887. if (onError) {
  59888. onError(msg, err);
  59889. }
  59890. else {
  59891. BABYLON.Tools.Log(msg);
  59892. throw err;
  59893. }
  59894. }
  59895. finally {
  59896. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  59897. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  59898. }
  59899. }
  59900. return false;
  59901. },
  59902. loadAssets: function (scene, data, rootUrl, onError) {
  59903. var container = loadAssets(scene, data, rootUrl, onerror);
  59904. return container;
  59905. }
  59906. });
  59907. })(BABYLON || (BABYLON = {}));
  59908. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  59909. var BABYLON;
  59910. (function (BABYLON) {
  59911. var FilesInput = /** @class */ (function () {
  59912. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  59913. this.onProcessFileCallback = function () { return true; };
  59914. this._engine = engine;
  59915. this._currentScene = scene;
  59916. this._sceneLoadedCallback = sceneLoadedCallback;
  59917. this._progressCallback = progressCallback;
  59918. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  59919. this._textureLoadingCallback = textureLoadingCallback;
  59920. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  59921. this._onReloadCallback = onReloadCallback;
  59922. this._errorCallback = errorCallback;
  59923. }
  59924. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  59925. var _this = this;
  59926. if (elementToMonitor) {
  59927. this._elementToMonitor = elementToMonitor;
  59928. this._dragEnterHandler = function (e) { _this.drag(e); };
  59929. this._dragOverHandler = function (e) { _this.drag(e); };
  59930. this._dropHandler = function (e) { _this.drop(e); };
  59931. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  59932. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  59933. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  59934. }
  59935. };
  59936. FilesInput.prototype.dispose = function () {
  59937. if (!this._elementToMonitor) {
  59938. return;
  59939. }
  59940. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  59941. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  59942. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  59943. };
  59944. FilesInput.prototype.renderFunction = function () {
  59945. if (this._additionalRenderLoopLogicCallback) {
  59946. this._additionalRenderLoopLogicCallback();
  59947. }
  59948. if (this._currentScene) {
  59949. if (this._textureLoadingCallback) {
  59950. var remaining = this._currentScene.getWaitingItemsCount();
  59951. if (remaining > 0) {
  59952. this._textureLoadingCallback(remaining);
  59953. }
  59954. }
  59955. this._currentScene.render();
  59956. }
  59957. };
  59958. FilesInput.prototype.drag = function (e) {
  59959. e.stopPropagation();
  59960. e.preventDefault();
  59961. };
  59962. FilesInput.prototype.drop = function (eventDrop) {
  59963. eventDrop.stopPropagation();
  59964. eventDrop.preventDefault();
  59965. this.loadFiles(eventDrop);
  59966. };
  59967. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  59968. var _this = this;
  59969. var reader = folder.createReader();
  59970. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  59971. reader.readEntries(function (entries) {
  59972. remaining.count += entries.length;
  59973. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  59974. var entry = entries_1[_i];
  59975. if (entry.isFile) {
  59976. entry.file(function (file) {
  59977. file.correctName = relativePath + file.name;
  59978. files.push(file);
  59979. if (--remaining.count === 0) {
  59980. callback();
  59981. }
  59982. });
  59983. }
  59984. else if (entry.isDirectory) {
  59985. _this._traverseFolder(entry, files, remaining, callback);
  59986. }
  59987. }
  59988. if (--remaining.count) {
  59989. callback();
  59990. }
  59991. });
  59992. };
  59993. FilesInput.prototype._processFiles = function (files) {
  59994. for (var i = 0; i < files.length; i++) {
  59995. var name = files[i].correctName.toLowerCase();
  59996. var extension = name.split('.').pop();
  59997. if (!this.onProcessFileCallback(files[i], name, extension)) {
  59998. continue;
  59999. }
  60000. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  60001. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  60002. this._sceneFileToLoad = files[i];
  60003. }
  60004. else {
  60005. FilesInput.FilesToLoad[name] = files[i];
  60006. }
  60007. }
  60008. };
  60009. FilesInput.prototype.loadFiles = function (event) {
  60010. var _this = this;
  60011. if (this._startingProcessingFilesCallback)
  60012. this._startingProcessingFilesCallback();
  60013. // Handling data transfer via drag'n'drop
  60014. if (event && event.dataTransfer && event.dataTransfer.files) {
  60015. this._filesToLoad = event.dataTransfer.files;
  60016. }
  60017. // Handling files from input files
  60018. if (event && event.target && event.target.files) {
  60019. this._filesToLoad = event.target.files;
  60020. }
  60021. if (this._filesToLoad && this._filesToLoad.length > 0) {
  60022. var files_1 = new Array();
  60023. var folders = [];
  60024. var items = event.dataTransfer ? event.dataTransfer.items : null;
  60025. for (var i = 0; i < this._filesToLoad.length; i++) {
  60026. var fileToLoad = this._filesToLoad[i];
  60027. var name_1 = fileToLoad.name.toLowerCase();
  60028. var entry = void 0;
  60029. fileToLoad.correctName = name_1;
  60030. if (items) {
  60031. var item = items[i];
  60032. if (item.getAsEntry) {
  60033. entry = item.getAsEntry();
  60034. }
  60035. else if (item.webkitGetAsEntry) {
  60036. entry = item.webkitGetAsEntry();
  60037. }
  60038. }
  60039. if (!entry) {
  60040. files_1.push(fileToLoad);
  60041. }
  60042. else {
  60043. if (entry.isDirectory) {
  60044. folders.push(entry);
  60045. }
  60046. else {
  60047. files_1.push(fileToLoad);
  60048. }
  60049. }
  60050. }
  60051. if (folders.length === 0) {
  60052. this._processFiles(files_1);
  60053. this._processReload();
  60054. }
  60055. else {
  60056. var remaining = { count: folders.length };
  60057. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  60058. var folder = folders_1[_i];
  60059. this._traverseFolder(folder, files_1, remaining, function () {
  60060. _this._processFiles(files_1);
  60061. if (remaining.count === 0) {
  60062. _this._processReload();
  60063. }
  60064. });
  60065. }
  60066. }
  60067. }
  60068. };
  60069. FilesInput.prototype._processReload = function () {
  60070. if (this._onReloadCallback) {
  60071. this._onReloadCallback(this._sceneFileToLoad);
  60072. }
  60073. else {
  60074. this.reload();
  60075. }
  60076. };
  60077. FilesInput.prototype.reload = function () {
  60078. var _this = this;
  60079. // If a scene file has been provided
  60080. if (this._sceneFileToLoad) {
  60081. if (this._currentScene) {
  60082. if (BABYLON.Tools.errorsCount > 0) {
  60083. BABYLON.Tools.ClearLogCache();
  60084. }
  60085. this._engine.stopRenderLoop();
  60086. this._currentScene.dispose();
  60087. }
  60088. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  60089. _this._currentScene = newScene;
  60090. if (_this._sceneLoadedCallback) {
  60091. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  60092. }
  60093. // Wait for textures and shaders to be ready
  60094. _this._currentScene.executeWhenReady(function () {
  60095. _this._engine.runRenderLoop(function () {
  60096. _this.renderFunction();
  60097. });
  60098. });
  60099. }, function (progress) {
  60100. if (_this._progressCallback) {
  60101. _this._progressCallback(progress);
  60102. }
  60103. }, function (scene, message) {
  60104. _this._currentScene = scene;
  60105. if (_this._errorCallback) {
  60106. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  60107. }
  60108. });
  60109. }
  60110. else {
  60111. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  60112. }
  60113. };
  60114. FilesInput.FilesToLoad = {};
  60115. return FilesInput;
  60116. }());
  60117. BABYLON.FilesInput = FilesInput;
  60118. })(BABYLON || (BABYLON = {}));
  60119. //# sourceMappingURL=babylon.filesInput.js.map
  60120. var BABYLON;
  60121. (function (BABYLON) {
  60122. /**
  60123. * This class implement a typical dictionary using a string as key and the generic type T as value.
  60124. * The underlying implementation relies on an associative array to ensure the best performances.
  60125. * The value can be anything including 'null' but except 'undefined'
  60126. */
  60127. var StringDictionary = /** @class */ (function () {
  60128. function StringDictionary() {
  60129. this._count = 0;
  60130. this._data = {};
  60131. }
  60132. /**
  60133. * This will clear this dictionary and copy the content from the 'source' one.
  60134. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  60135. * @param source the dictionary to take the content from and copy to this dictionary
  60136. */
  60137. StringDictionary.prototype.copyFrom = function (source) {
  60138. var _this = this;
  60139. this.clear();
  60140. source.forEach(function (t, v) { return _this.add(t, v); });
  60141. };
  60142. /**
  60143. * Get a value based from its key
  60144. * @param key the given key to get the matching value from
  60145. * @return the value if found, otherwise undefined is returned
  60146. */
  60147. StringDictionary.prototype.get = function (key) {
  60148. var val = this._data[key];
  60149. if (val !== undefined) {
  60150. return val;
  60151. }
  60152. return undefined;
  60153. };
  60154. /**
  60155. * Get a value from its key or add it if it doesn't exist.
  60156. * This method will ensure you that a given key/data will be present in the dictionary.
  60157. * @param key the given key to get the matching value from
  60158. * @param factory the factory that will create the value if the key is not present in the dictionary.
  60159. * The factory will only be invoked if there's no data for the given key.
  60160. * @return the value corresponding to the key.
  60161. */
  60162. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  60163. var val = this.get(key);
  60164. if (val !== undefined) {
  60165. return val;
  60166. }
  60167. val = factory(key);
  60168. if (val) {
  60169. this.add(key, val);
  60170. }
  60171. return val;
  60172. };
  60173. /**
  60174. * Get a value from its key if present in the dictionary otherwise add it
  60175. * @param key the key to get the value from
  60176. * @param val if there's no such key/value pair in the dictionary add it with this value
  60177. * @return the value corresponding to the key
  60178. */
  60179. StringDictionary.prototype.getOrAdd = function (key, val) {
  60180. var curVal = this.get(key);
  60181. if (curVal !== undefined) {
  60182. return curVal;
  60183. }
  60184. this.add(key, val);
  60185. return val;
  60186. };
  60187. /**
  60188. * Check if there's a given key in the dictionary
  60189. * @param key the key to check for
  60190. * @return true if the key is present, false otherwise
  60191. */
  60192. StringDictionary.prototype.contains = function (key) {
  60193. return this._data[key] !== undefined;
  60194. };
  60195. /**
  60196. * Add a new key and its corresponding value
  60197. * @param key the key to add
  60198. * @param value the value corresponding to the key
  60199. * @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
  60200. */
  60201. StringDictionary.prototype.add = function (key, value) {
  60202. if (this._data[key] !== undefined) {
  60203. return false;
  60204. }
  60205. this._data[key] = value;
  60206. ++this._count;
  60207. return true;
  60208. };
  60209. StringDictionary.prototype.set = function (key, value) {
  60210. if (this._data[key] === undefined) {
  60211. return false;
  60212. }
  60213. this._data[key] = value;
  60214. return true;
  60215. };
  60216. /**
  60217. * Get the element of the given key and remove it from the dictionary
  60218. * @param key
  60219. */
  60220. StringDictionary.prototype.getAndRemove = function (key) {
  60221. var val = this.get(key);
  60222. if (val !== undefined) {
  60223. delete this._data[key];
  60224. --this._count;
  60225. return val;
  60226. }
  60227. return null;
  60228. };
  60229. /**
  60230. * Remove a key/value from the dictionary.
  60231. * @param key the key to remove
  60232. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  60233. */
  60234. StringDictionary.prototype.remove = function (key) {
  60235. if (this.contains(key)) {
  60236. delete this._data[key];
  60237. --this._count;
  60238. return true;
  60239. }
  60240. return false;
  60241. };
  60242. /**
  60243. * Clear the whole content of the dictionary
  60244. */
  60245. StringDictionary.prototype.clear = function () {
  60246. this._data = {};
  60247. this._count = 0;
  60248. };
  60249. Object.defineProperty(StringDictionary.prototype, "count", {
  60250. get: function () {
  60251. return this._count;
  60252. },
  60253. enumerable: true,
  60254. configurable: true
  60255. });
  60256. /**
  60257. * Execute a callback on each key/val of the dictionary.
  60258. * Note that you can remove any element in this dictionary in the callback implementation
  60259. * @param callback the callback to execute on a given key/value pair
  60260. */
  60261. StringDictionary.prototype.forEach = function (callback) {
  60262. for (var cur in this._data) {
  60263. var val = this._data[cur];
  60264. callback(cur, val);
  60265. }
  60266. };
  60267. /**
  60268. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  60269. * If the callback returns null or undefined the method will iterate to the next key/value pair
  60270. * Note that you can remove any element in this dictionary in the callback implementation
  60271. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  60272. */
  60273. StringDictionary.prototype.first = function (callback) {
  60274. for (var cur in this._data) {
  60275. var val = this._data[cur];
  60276. var res = callback(cur, val);
  60277. if (res) {
  60278. return res;
  60279. }
  60280. }
  60281. return null;
  60282. };
  60283. return StringDictionary;
  60284. }());
  60285. BABYLON.StringDictionary = StringDictionary;
  60286. })(BABYLON || (BABYLON = {}));
  60287. //# sourceMappingURL=babylon.stringDictionary.js.map
  60288. var BABYLON;
  60289. (function (BABYLON) {
  60290. var Tags = /** @class */ (function () {
  60291. function Tags() {
  60292. }
  60293. Tags.EnableFor = function (obj) {
  60294. obj._tags = obj._tags || {};
  60295. obj.hasTags = function () {
  60296. return Tags.HasTags(obj);
  60297. };
  60298. obj.addTags = function (tagsString) {
  60299. return Tags.AddTagsTo(obj, tagsString);
  60300. };
  60301. obj.removeTags = function (tagsString) {
  60302. return Tags.RemoveTagsFrom(obj, tagsString);
  60303. };
  60304. obj.matchesTagsQuery = function (tagsQuery) {
  60305. return Tags.MatchesQuery(obj, tagsQuery);
  60306. };
  60307. };
  60308. Tags.DisableFor = function (obj) {
  60309. delete obj._tags;
  60310. delete obj.hasTags;
  60311. delete obj.addTags;
  60312. delete obj.removeTags;
  60313. delete obj.matchesTagsQuery;
  60314. };
  60315. Tags.HasTags = function (obj) {
  60316. if (!obj._tags) {
  60317. return false;
  60318. }
  60319. return !BABYLON.Tools.IsEmpty(obj._tags);
  60320. };
  60321. Tags.GetTags = function (obj, asString) {
  60322. if (asString === void 0) { asString = true; }
  60323. if (!obj._tags) {
  60324. return null;
  60325. }
  60326. if (asString) {
  60327. var tagsArray = [];
  60328. for (var tag in obj._tags) {
  60329. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  60330. tagsArray.push(tag);
  60331. }
  60332. }
  60333. return tagsArray.join(" ");
  60334. }
  60335. else {
  60336. return obj._tags;
  60337. }
  60338. };
  60339. // the tags 'true' and 'false' are reserved and cannot be used as tags
  60340. // a tag cannot start with '||', '&&', and '!'
  60341. // it cannot contain whitespaces
  60342. Tags.AddTagsTo = function (obj, tagsString) {
  60343. if (!tagsString) {
  60344. return;
  60345. }
  60346. if (typeof tagsString !== "string") {
  60347. return;
  60348. }
  60349. var tags = tagsString.split(" ");
  60350. tags.forEach(function (tag, index, array) {
  60351. Tags._AddTagTo(obj, tag);
  60352. });
  60353. };
  60354. Tags._AddTagTo = function (obj, tag) {
  60355. tag = tag.trim();
  60356. if (tag === "" || tag === "true" || tag === "false") {
  60357. return;
  60358. }
  60359. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  60360. return;
  60361. }
  60362. Tags.EnableFor(obj);
  60363. obj._tags[tag] = true;
  60364. };
  60365. Tags.RemoveTagsFrom = function (obj, tagsString) {
  60366. if (!Tags.HasTags(obj)) {
  60367. return;
  60368. }
  60369. var tags = tagsString.split(" ");
  60370. for (var t in tags) {
  60371. Tags._RemoveTagFrom(obj, tags[t]);
  60372. }
  60373. };
  60374. Tags._RemoveTagFrom = function (obj, tag) {
  60375. delete obj._tags[tag];
  60376. };
  60377. Tags.MatchesQuery = function (obj, tagsQuery) {
  60378. if (tagsQuery === undefined) {
  60379. return true;
  60380. }
  60381. if (tagsQuery === "") {
  60382. return Tags.HasTags(obj);
  60383. }
  60384. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  60385. };
  60386. return Tags;
  60387. }());
  60388. BABYLON.Tags = Tags;
  60389. })(BABYLON || (BABYLON = {}));
  60390. //# sourceMappingURL=babylon.tags.js.map
  60391. var BABYLON;
  60392. (function (BABYLON) {
  60393. var AndOrNotEvaluator = /** @class */ (function () {
  60394. function AndOrNotEvaluator() {
  60395. }
  60396. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  60397. if (!query.match(/\([^\(\)]*\)/g)) {
  60398. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  60399. }
  60400. else {
  60401. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  60402. // remove parenthesis
  60403. r = r.slice(1, r.length - 1);
  60404. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  60405. });
  60406. }
  60407. if (query === "true") {
  60408. return true;
  60409. }
  60410. if (query === "false") {
  60411. return false;
  60412. }
  60413. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  60414. };
  60415. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  60416. evaluateCallback = evaluateCallback || (function (r) {
  60417. return r === "true" ? true : false;
  60418. });
  60419. var result;
  60420. var or = parenthesisContent.split("||");
  60421. for (var i in or) {
  60422. if (or.hasOwnProperty(i)) {
  60423. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  60424. var and = ori.split("&&");
  60425. if (and.length > 1) {
  60426. for (var j = 0; j < and.length; ++j) {
  60427. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  60428. if (andj !== "true" && andj !== "false") {
  60429. if (andj[0] === "!") {
  60430. result = !evaluateCallback(andj.substring(1));
  60431. }
  60432. else {
  60433. result = evaluateCallback(andj);
  60434. }
  60435. }
  60436. else {
  60437. result = andj === "true" ? true : false;
  60438. }
  60439. if (!result) {
  60440. ori = "false";
  60441. break;
  60442. }
  60443. }
  60444. }
  60445. if (result || ori === "true") {
  60446. result = true;
  60447. break;
  60448. }
  60449. // result equals false (or undefined)
  60450. if (ori !== "true" && ori !== "false") {
  60451. if (ori[0] === "!") {
  60452. result = !evaluateCallback(ori.substring(1));
  60453. }
  60454. else {
  60455. result = evaluateCallback(ori);
  60456. }
  60457. }
  60458. else {
  60459. result = ori === "true" ? true : false;
  60460. }
  60461. }
  60462. }
  60463. // the whole parenthesis scope is replaced by 'true' or 'false'
  60464. return result ? "true" : "false";
  60465. };
  60466. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  60467. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  60468. // remove whitespaces
  60469. r = r.replace(/[\s]/g, function () { return ""; });
  60470. return r.length % 2 ? "!" : "";
  60471. });
  60472. booleanString = booleanString.trim();
  60473. if (booleanString === "!true") {
  60474. booleanString = "false";
  60475. }
  60476. else if (booleanString === "!false") {
  60477. booleanString = "true";
  60478. }
  60479. return booleanString;
  60480. };
  60481. return AndOrNotEvaluator;
  60482. }());
  60483. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  60484. })(BABYLON || (BABYLON = {}));
  60485. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  60486. var BABYLON;
  60487. (function (BABYLON) {
  60488. var Database = /** @class */ (function () {
  60489. function Database(urlToScene, callbackManifestChecked) {
  60490. // Handling various flavors of prefixed version of IndexedDB
  60491. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  60492. this.callbackManifestChecked = callbackManifestChecked;
  60493. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  60494. this.db = null;
  60495. this._enableSceneOffline = false;
  60496. this._enableTexturesOffline = false;
  60497. this.manifestVersionFound = 0;
  60498. this.mustUpdateRessources = false;
  60499. this.hasReachedQuota = false;
  60500. if (!Database.IDBStorageEnabled) {
  60501. this.callbackManifestChecked(true);
  60502. }
  60503. else {
  60504. this.checkManifestFile();
  60505. }
  60506. }
  60507. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  60508. get: function () {
  60509. return this._enableSceneOffline;
  60510. },
  60511. enumerable: true,
  60512. configurable: true
  60513. });
  60514. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  60515. get: function () {
  60516. return this._enableTexturesOffline;
  60517. },
  60518. enumerable: true,
  60519. configurable: true
  60520. });
  60521. Database.prototype.checkManifestFile = function () {
  60522. var _this = this;
  60523. var noManifestFile = function () {
  60524. _this._enableSceneOffline = false;
  60525. _this._enableTexturesOffline = false;
  60526. _this.callbackManifestChecked(false);
  60527. };
  60528. var timeStampUsed = false;
  60529. var manifestURL = this.currentSceneUrl + ".manifest";
  60530. var xhr = new XMLHttpRequest();
  60531. if (navigator.onLine) {
  60532. // Adding a timestamp to by-pass browsers' cache
  60533. timeStampUsed = true;
  60534. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  60535. }
  60536. xhr.open("GET", manifestURL, true);
  60537. xhr.addEventListener("load", function () {
  60538. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  60539. try {
  60540. var manifestFile = JSON.parse(xhr.response);
  60541. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  60542. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  60543. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  60544. _this.manifestVersionFound = manifestFile.version;
  60545. }
  60546. if (_this.callbackManifestChecked) {
  60547. _this.callbackManifestChecked(true);
  60548. }
  60549. }
  60550. catch (ex) {
  60551. noManifestFile();
  60552. }
  60553. }
  60554. else {
  60555. noManifestFile();
  60556. }
  60557. }, false);
  60558. xhr.addEventListener("error", function (event) {
  60559. if (timeStampUsed) {
  60560. timeStampUsed = false;
  60561. // Let's retry without the timeStamp
  60562. // It could fail when coupled with HTML5 Offline API
  60563. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  60564. xhr.open("GET", retryManifestURL, true);
  60565. xhr.send();
  60566. }
  60567. else {
  60568. noManifestFile();
  60569. }
  60570. }, false);
  60571. try {
  60572. xhr.send();
  60573. }
  60574. catch (ex) {
  60575. BABYLON.Tools.Error("Error on XHR send request.");
  60576. this.callbackManifestChecked(false);
  60577. }
  60578. };
  60579. Database.prototype.openAsync = function (successCallback, errorCallback) {
  60580. var _this = this;
  60581. var handleError = function () {
  60582. _this.isSupported = false;
  60583. if (errorCallback)
  60584. errorCallback();
  60585. };
  60586. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  60587. // Your browser doesn't support IndexedDB
  60588. this.isSupported = false;
  60589. if (errorCallback)
  60590. errorCallback();
  60591. }
  60592. else {
  60593. // If the DB hasn't been opened or created yet
  60594. if (!this.db) {
  60595. this.hasReachedQuota = false;
  60596. this.isSupported = true;
  60597. var request = this.idbFactory.open("babylonjs", 1);
  60598. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  60599. request.onerror = function (event) {
  60600. handleError();
  60601. };
  60602. // executes when a version change transaction cannot complete due to other active transactions
  60603. request.onblocked = function (event) {
  60604. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  60605. handleError();
  60606. };
  60607. // DB has been opened successfully
  60608. request.onsuccess = function (event) {
  60609. _this.db = request.result;
  60610. successCallback();
  60611. };
  60612. // Initialization of the DB. Creating Scenes & Textures stores
  60613. request.onupgradeneeded = function (event) {
  60614. _this.db = (event.target).result;
  60615. if (_this.db) {
  60616. try {
  60617. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  60618. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  60619. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  60620. }
  60621. catch (ex) {
  60622. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  60623. handleError();
  60624. }
  60625. }
  60626. };
  60627. }
  60628. else {
  60629. if (successCallback)
  60630. successCallback();
  60631. }
  60632. }
  60633. };
  60634. Database.prototype.loadImageFromDB = function (url, image) {
  60635. var _this = this;
  60636. var completeURL = Database.ReturnFullUrlLocation(url);
  60637. var saveAndLoadImage = function () {
  60638. if (!_this.hasReachedQuota && _this.db !== null) {
  60639. // the texture is not yet in the DB, let's try to save it
  60640. _this._saveImageIntoDBAsync(completeURL, image);
  60641. }
  60642. else {
  60643. image.src = url;
  60644. }
  60645. };
  60646. if (!this.mustUpdateRessources) {
  60647. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  60648. }
  60649. else {
  60650. saveAndLoadImage();
  60651. }
  60652. };
  60653. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  60654. if (this.isSupported && this.db !== null) {
  60655. var texture;
  60656. var transaction = this.db.transaction(["textures"]);
  60657. transaction.onabort = function (event) {
  60658. image.src = url;
  60659. };
  60660. transaction.oncomplete = function (event) {
  60661. var blobTextureURL;
  60662. if (texture) {
  60663. var URL = window.URL || window.webkitURL;
  60664. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  60665. image.onerror = function () {
  60666. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  60667. image.src = url;
  60668. };
  60669. image.src = blobTextureURL;
  60670. }
  60671. else {
  60672. notInDBCallback();
  60673. }
  60674. };
  60675. var getRequest = transaction.objectStore("textures").get(url);
  60676. getRequest.onsuccess = function (event) {
  60677. texture = (event.target).result;
  60678. };
  60679. getRequest.onerror = function (event) {
  60680. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  60681. image.src = url;
  60682. };
  60683. }
  60684. else {
  60685. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  60686. image.src = url;
  60687. }
  60688. };
  60689. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  60690. var _this = this;
  60691. if (this.isSupported) {
  60692. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  60693. var generateBlobUrl = function () {
  60694. var blobTextureURL;
  60695. if (blob) {
  60696. var URL = window.URL || window.webkitURL;
  60697. try {
  60698. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  60699. }
  60700. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  60701. catch (ex) {
  60702. blobTextureURL = URL.createObjectURL(blob);
  60703. }
  60704. }
  60705. if (blobTextureURL) {
  60706. image.src = blobTextureURL;
  60707. }
  60708. };
  60709. if (Database.IsUASupportingBlobStorage) {
  60710. var xhr = new XMLHttpRequest(), blob;
  60711. xhr.open("GET", url, true);
  60712. xhr.responseType = "blob";
  60713. xhr.addEventListener("load", function () {
  60714. if (xhr.status === 200 && _this.db) {
  60715. // Blob as response (XHR2)
  60716. blob = xhr.response;
  60717. var transaction = _this.db.transaction(["textures"], "readwrite");
  60718. // the transaction could abort because of a QuotaExceededError error
  60719. transaction.onabort = function (event) {
  60720. try {
  60721. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  60722. var srcElement = (event.srcElement || event.target);
  60723. var error = srcElement.error;
  60724. if (error && error.name === "QuotaExceededError") {
  60725. _this.hasReachedQuota = true;
  60726. }
  60727. }
  60728. catch (ex) { }
  60729. generateBlobUrl();
  60730. };
  60731. transaction.oncomplete = function (event) {
  60732. generateBlobUrl();
  60733. };
  60734. var newTexture = { textureUrl: url, data: blob };
  60735. try {
  60736. // Put the blob into the dabase
  60737. var addRequest = transaction.objectStore("textures").put(newTexture);
  60738. addRequest.onsuccess = function (event) {
  60739. };
  60740. addRequest.onerror = function (event) {
  60741. generateBlobUrl();
  60742. };
  60743. }
  60744. catch (ex) {
  60745. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  60746. if (ex.code === 25) {
  60747. Database.IsUASupportingBlobStorage = false;
  60748. }
  60749. image.src = url;
  60750. }
  60751. }
  60752. else {
  60753. image.src = url;
  60754. }
  60755. }, false);
  60756. xhr.addEventListener("error", function (event) {
  60757. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  60758. image.src = url;
  60759. }, false);
  60760. xhr.send();
  60761. }
  60762. else {
  60763. image.src = url;
  60764. }
  60765. }
  60766. else {
  60767. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  60768. image.src = url;
  60769. }
  60770. };
  60771. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  60772. var _this = this;
  60773. var updateVersion = function () {
  60774. // the version is not yet in the DB or we need to update it
  60775. _this._saveVersionIntoDBAsync(url, versionLoaded);
  60776. };
  60777. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  60778. };
  60779. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  60780. var _this = this;
  60781. if (this.isSupported && this.db) {
  60782. var version;
  60783. try {
  60784. var transaction = this.db.transaction(["versions"]);
  60785. transaction.oncomplete = function (event) {
  60786. if (version) {
  60787. // If the version in the JSON file is > than the version in DB
  60788. if (_this.manifestVersionFound > version.data) {
  60789. _this.mustUpdateRessources = true;
  60790. updateInDBCallback();
  60791. }
  60792. else {
  60793. callback(version.data);
  60794. }
  60795. }
  60796. else {
  60797. _this.mustUpdateRessources = true;
  60798. updateInDBCallback();
  60799. }
  60800. };
  60801. transaction.onabort = function (event) {
  60802. callback(-1);
  60803. };
  60804. var getRequest = transaction.objectStore("versions").get(url);
  60805. getRequest.onsuccess = function (event) {
  60806. version = (event.target).result;
  60807. };
  60808. getRequest.onerror = function (event) {
  60809. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  60810. callback(-1);
  60811. };
  60812. }
  60813. catch (ex) {
  60814. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  60815. callback(-1);
  60816. }
  60817. }
  60818. else {
  60819. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  60820. callback(-1);
  60821. }
  60822. };
  60823. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  60824. var _this = this;
  60825. if (this.isSupported && !this.hasReachedQuota && this.db) {
  60826. try {
  60827. // Open a transaction to the database
  60828. var transaction = this.db.transaction(["versions"], "readwrite");
  60829. // the transaction could abort because of a QuotaExceededError error
  60830. transaction.onabort = function (event) {
  60831. try {
  60832. var error = event.srcElement['error'];
  60833. if (error && error.name === "QuotaExceededError") {
  60834. _this.hasReachedQuota = true;
  60835. }
  60836. }
  60837. catch (ex) { }
  60838. callback(-1);
  60839. };
  60840. transaction.oncomplete = function (event) {
  60841. callback(_this.manifestVersionFound);
  60842. };
  60843. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  60844. // Put the scene into the database
  60845. var addRequest = transaction.objectStore("versions").put(newVersion);
  60846. addRequest.onsuccess = function (event) {
  60847. };
  60848. addRequest.onerror = function (event) {
  60849. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  60850. };
  60851. }
  60852. catch (ex) {
  60853. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  60854. callback(-1);
  60855. }
  60856. }
  60857. else {
  60858. callback(-1);
  60859. }
  60860. };
  60861. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  60862. var _this = this;
  60863. var completeUrl = Database.ReturnFullUrlLocation(url);
  60864. var saveAndLoadFile = function () {
  60865. // the scene is not yet in the DB, let's try to save it
  60866. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  60867. };
  60868. this._checkVersionFromDB(completeUrl, function (version) {
  60869. if (version !== -1) {
  60870. if (!_this.mustUpdateRessources) {
  60871. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  60872. }
  60873. else {
  60874. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  60875. }
  60876. }
  60877. else {
  60878. if (errorCallback) {
  60879. errorCallback();
  60880. }
  60881. }
  60882. });
  60883. };
  60884. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  60885. if (this.isSupported && this.db) {
  60886. var targetStore;
  60887. if (url.indexOf(".babylon") !== -1) {
  60888. targetStore = "scenes";
  60889. }
  60890. else {
  60891. targetStore = "textures";
  60892. }
  60893. var file;
  60894. var transaction = this.db.transaction([targetStore]);
  60895. transaction.oncomplete = function (event) {
  60896. if (file) {
  60897. callback(file.data);
  60898. }
  60899. else {
  60900. notInDBCallback();
  60901. }
  60902. };
  60903. transaction.onabort = function (event) {
  60904. notInDBCallback();
  60905. };
  60906. var getRequest = transaction.objectStore(targetStore).get(url);
  60907. getRequest.onsuccess = function (event) {
  60908. file = (event.target).result;
  60909. };
  60910. getRequest.onerror = function (event) {
  60911. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  60912. notInDBCallback();
  60913. };
  60914. }
  60915. else {
  60916. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  60917. callback();
  60918. }
  60919. };
  60920. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  60921. var _this = this;
  60922. if (this.isSupported) {
  60923. var targetStore;
  60924. if (url.indexOf(".babylon") !== -1) {
  60925. targetStore = "scenes";
  60926. }
  60927. else {
  60928. targetStore = "textures";
  60929. }
  60930. // Create XHR
  60931. var xhr = new XMLHttpRequest();
  60932. var fileData;
  60933. xhr.open("GET", url, true);
  60934. if (useArrayBuffer) {
  60935. xhr.responseType = "arraybuffer";
  60936. }
  60937. if (progressCallback) {
  60938. xhr.onprogress = progressCallback;
  60939. }
  60940. xhr.addEventListener("load", function () {
  60941. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  60942. // Blob as response (XHR2)
  60943. //fileData = xhr.responseText;
  60944. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  60945. if (!_this.hasReachedQuota && _this.db) {
  60946. // Open a transaction to the database
  60947. var transaction = _this.db.transaction([targetStore], "readwrite");
  60948. // the transaction could abort because of a QuotaExceededError error
  60949. transaction.onabort = function (event) {
  60950. try {
  60951. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  60952. var error = event.srcElement['error'];
  60953. if (error && error.name === "QuotaExceededError") {
  60954. _this.hasReachedQuota = true;
  60955. }
  60956. }
  60957. catch (ex) { }
  60958. callback(fileData);
  60959. };
  60960. transaction.oncomplete = function (event) {
  60961. callback(fileData);
  60962. };
  60963. var newFile;
  60964. if (targetStore === "scenes") {
  60965. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  60966. }
  60967. else {
  60968. newFile = { textureUrl: url, data: fileData };
  60969. }
  60970. try {
  60971. // Put the scene into the database
  60972. var addRequest = transaction.objectStore(targetStore).put(newFile);
  60973. addRequest.onsuccess = function (event) {
  60974. };
  60975. addRequest.onerror = function (event) {
  60976. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  60977. };
  60978. }
  60979. catch (ex) {
  60980. callback(fileData);
  60981. }
  60982. }
  60983. else {
  60984. callback(fileData);
  60985. }
  60986. }
  60987. else {
  60988. callback();
  60989. }
  60990. }, false);
  60991. xhr.addEventListener("error", function (event) {
  60992. BABYLON.Tools.Error("error on XHR request.");
  60993. callback();
  60994. }, false);
  60995. xhr.send();
  60996. }
  60997. else {
  60998. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  60999. callback();
  61000. }
  61001. };
  61002. Database.IsUASupportingBlobStorage = true;
  61003. Database.IDBStorageEnabled = true;
  61004. Database.parseURL = function (url) {
  61005. var a = document.createElement('a');
  61006. a.href = url;
  61007. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  61008. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  61009. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  61010. return absLocation;
  61011. };
  61012. Database.ReturnFullUrlLocation = function (url) {
  61013. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  61014. return (Database.parseURL(window.location.href) + url);
  61015. }
  61016. else {
  61017. return url;
  61018. }
  61019. };
  61020. return Database;
  61021. }());
  61022. BABYLON.Database = Database;
  61023. })(BABYLON || (BABYLON = {}));
  61024. //# sourceMappingURL=babylon.database.js.map
  61025. var BABYLON;
  61026. (function (BABYLON) {
  61027. var FresnelParameters = /** @class */ (function () {
  61028. function FresnelParameters() {
  61029. this._isEnabled = true;
  61030. this.leftColor = BABYLON.Color3.White();
  61031. this.rightColor = BABYLON.Color3.Black();
  61032. this.bias = 0;
  61033. this.power = 1;
  61034. }
  61035. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  61036. get: function () {
  61037. return this._isEnabled;
  61038. },
  61039. set: function (value) {
  61040. if (this._isEnabled === value) {
  61041. return;
  61042. }
  61043. this._isEnabled = value;
  61044. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  61045. },
  61046. enumerable: true,
  61047. configurable: true
  61048. });
  61049. FresnelParameters.prototype.clone = function () {
  61050. var newFresnelParameters = new FresnelParameters();
  61051. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  61052. return newFresnelParameters;
  61053. };
  61054. FresnelParameters.prototype.serialize = function () {
  61055. var serializationObject = {};
  61056. serializationObject.isEnabled = this.isEnabled;
  61057. serializationObject.leftColor = this.leftColor;
  61058. serializationObject.rightColor = this.rightColor;
  61059. serializationObject.bias = this.bias;
  61060. serializationObject.power = this.power;
  61061. return serializationObject;
  61062. };
  61063. FresnelParameters.Parse = function (parsedFresnelParameters) {
  61064. var fresnelParameters = new FresnelParameters();
  61065. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  61066. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  61067. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  61068. fresnelParameters.bias = parsedFresnelParameters.bias;
  61069. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  61070. return fresnelParameters;
  61071. };
  61072. return FresnelParameters;
  61073. }());
  61074. BABYLON.FresnelParameters = FresnelParameters;
  61075. })(BABYLON || (BABYLON = {}));
  61076. //# sourceMappingURL=babylon.fresnelParameters.js.map
  61077. var BABYLON;
  61078. (function (BABYLON) {
  61079. var MultiMaterial = /** @class */ (function (_super) {
  61080. __extends(MultiMaterial, _super);
  61081. function MultiMaterial(name, scene) {
  61082. var _this = _super.call(this, name, scene, true) || this;
  61083. scene.multiMaterials.push(_this);
  61084. _this.subMaterials = new Array();
  61085. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  61086. return _this;
  61087. }
  61088. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  61089. get: function () {
  61090. return this._subMaterials;
  61091. },
  61092. set: function (value) {
  61093. this._subMaterials = value;
  61094. this._hookArray(value);
  61095. },
  61096. enumerable: true,
  61097. configurable: true
  61098. });
  61099. MultiMaterial.prototype._hookArray = function (array) {
  61100. var _this = this;
  61101. var oldPush = array.push;
  61102. array.push = function () {
  61103. var items = [];
  61104. for (var _i = 0; _i < arguments.length; _i++) {
  61105. items[_i] = arguments[_i];
  61106. }
  61107. var result = oldPush.apply(array, items);
  61108. _this._markAllSubMeshesAsTexturesDirty();
  61109. return result;
  61110. };
  61111. var oldSplice = array.splice;
  61112. array.splice = function (index, deleteCount) {
  61113. var deleted = oldSplice.apply(array, [index, deleteCount]);
  61114. _this._markAllSubMeshesAsTexturesDirty();
  61115. return deleted;
  61116. };
  61117. };
  61118. // Properties
  61119. MultiMaterial.prototype.getSubMaterial = function (index) {
  61120. if (index < 0 || index >= this.subMaterials.length) {
  61121. return this.getScene().defaultMaterial;
  61122. }
  61123. return this.subMaterials[index];
  61124. };
  61125. MultiMaterial.prototype.getActiveTextures = function () {
  61126. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  61127. if (subMaterial) {
  61128. return subMaterial.getActiveTextures();
  61129. }
  61130. else {
  61131. return [];
  61132. }
  61133. }));
  61134. var _a;
  61135. };
  61136. // Methods
  61137. MultiMaterial.prototype.getClassName = function () {
  61138. return "MultiMaterial";
  61139. };
  61140. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  61141. for (var index = 0; index < this.subMaterials.length; index++) {
  61142. var subMaterial = this.subMaterials[index];
  61143. if (subMaterial) {
  61144. if (subMaterial.storeEffectOnSubMeshes) {
  61145. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  61146. return false;
  61147. }
  61148. continue;
  61149. }
  61150. if (!subMaterial.isReady(mesh)) {
  61151. return false;
  61152. }
  61153. }
  61154. }
  61155. return true;
  61156. };
  61157. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  61158. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  61159. for (var index = 0; index < this.subMaterials.length; index++) {
  61160. var subMaterial = null;
  61161. var current = this.subMaterials[index];
  61162. if (cloneChildren && current) {
  61163. subMaterial = current.clone(name + "-" + current.name);
  61164. }
  61165. else {
  61166. subMaterial = this.subMaterials[index];
  61167. }
  61168. newMultiMaterial.subMaterials.push(subMaterial);
  61169. }
  61170. return newMultiMaterial;
  61171. };
  61172. MultiMaterial.prototype.serialize = function () {
  61173. var serializationObject = {};
  61174. serializationObject.name = this.name;
  61175. serializationObject.id = this.id;
  61176. if (BABYLON.Tags) {
  61177. serializationObject.tags = BABYLON.Tags.GetTags(this);
  61178. }
  61179. serializationObject.materials = [];
  61180. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  61181. var subMat = this.subMaterials[matIndex];
  61182. if (subMat) {
  61183. serializationObject.materials.push(subMat.id);
  61184. }
  61185. else {
  61186. serializationObject.materials.push(null);
  61187. }
  61188. }
  61189. return serializationObject;
  61190. };
  61191. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  61192. var scene = this.getScene();
  61193. if (!scene) {
  61194. return;
  61195. }
  61196. var index = scene.multiMaterials.indexOf(this);
  61197. if (index >= 0) {
  61198. scene.multiMaterials.splice(index, 1);
  61199. }
  61200. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  61201. };
  61202. return MultiMaterial;
  61203. }(BABYLON.Material));
  61204. BABYLON.MultiMaterial = MultiMaterial;
  61205. })(BABYLON || (BABYLON = {}));
  61206. //# sourceMappingURL=babylon.multiMaterial.js.map
  61207. var BABYLON;
  61208. (function (BABYLON) {
  61209. var FreeCameraTouchInput = /** @class */ (function () {
  61210. function FreeCameraTouchInput() {
  61211. this._offsetX = null;
  61212. this._offsetY = null;
  61213. this._pointerPressed = new Array();
  61214. this.touchAngularSensibility = 200000.0;
  61215. this.touchMoveSensibility = 250.0;
  61216. }
  61217. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  61218. var _this = this;
  61219. var previousPosition = null;
  61220. if (this._pointerInput === undefined) {
  61221. this._onLostFocus = function (evt) {
  61222. _this._offsetX = null;
  61223. _this._offsetY = null;
  61224. };
  61225. this._pointerInput = function (p, s) {
  61226. var evt = p.event;
  61227. if (evt.pointerType === "mouse") {
  61228. return;
  61229. }
  61230. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  61231. if (!noPreventDefault) {
  61232. evt.preventDefault();
  61233. }
  61234. _this._pointerPressed.push(evt.pointerId);
  61235. if (_this._pointerPressed.length !== 1) {
  61236. return;
  61237. }
  61238. previousPosition = {
  61239. x: evt.clientX,
  61240. y: evt.clientY
  61241. };
  61242. }
  61243. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  61244. if (!noPreventDefault) {
  61245. evt.preventDefault();
  61246. }
  61247. var index = _this._pointerPressed.indexOf(evt.pointerId);
  61248. if (index === -1) {
  61249. return;
  61250. }
  61251. _this._pointerPressed.splice(index, 1);
  61252. if (index != 0) {
  61253. return;
  61254. }
  61255. previousPosition = null;
  61256. _this._offsetX = null;
  61257. _this._offsetY = null;
  61258. }
  61259. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  61260. if (!noPreventDefault) {
  61261. evt.preventDefault();
  61262. }
  61263. if (!previousPosition) {
  61264. return;
  61265. }
  61266. var index = _this._pointerPressed.indexOf(evt.pointerId);
  61267. if (index != 0) {
  61268. return;
  61269. }
  61270. _this._offsetX = evt.clientX - previousPosition.x;
  61271. _this._offsetY = -(evt.clientY - previousPosition.y);
  61272. }
  61273. };
  61274. }
  61275. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  61276. if (this._onLostFocus) {
  61277. element.addEventListener("blur", this._onLostFocus);
  61278. }
  61279. };
  61280. FreeCameraTouchInput.prototype.detachControl = function (element) {
  61281. if (this._pointerInput && element) {
  61282. if (this._observer) {
  61283. this.camera.getScene().onPointerObservable.remove(this._observer);
  61284. this._observer = null;
  61285. }
  61286. if (this._onLostFocus) {
  61287. element.removeEventListener("blur", this._onLostFocus);
  61288. this._onLostFocus = null;
  61289. }
  61290. this._pointerPressed = [];
  61291. this._offsetX = null;
  61292. this._offsetY = null;
  61293. }
  61294. };
  61295. FreeCameraTouchInput.prototype.checkInputs = function () {
  61296. if (this._offsetX && this._offsetY) {
  61297. var camera = this.camera;
  61298. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  61299. if (this._pointerPressed.length > 1) {
  61300. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  61301. }
  61302. else {
  61303. var speed = camera._computeLocalCameraSpeed();
  61304. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  61305. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  61306. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  61307. }
  61308. }
  61309. };
  61310. FreeCameraTouchInput.prototype.getClassName = function () {
  61311. return "FreeCameraTouchInput";
  61312. };
  61313. FreeCameraTouchInput.prototype.getSimpleName = function () {
  61314. return "touch";
  61315. };
  61316. __decorate([
  61317. BABYLON.serialize()
  61318. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  61319. __decorate([
  61320. BABYLON.serialize()
  61321. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  61322. return FreeCameraTouchInput;
  61323. }());
  61324. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  61325. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  61326. })(BABYLON || (BABYLON = {}));
  61327. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  61328. var BABYLON;
  61329. (function (BABYLON) {
  61330. // We're mainly based on the logic defined into the FreeCamera code
  61331. var TouchCamera = /** @class */ (function (_super) {
  61332. __extends(TouchCamera, _super);
  61333. //-- end properties for backward compatibility for inputs
  61334. function TouchCamera(name, position, scene) {
  61335. var _this = _super.call(this, name, position, scene) || this;
  61336. _this.inputs.addTouch();
  61337. _this._setupInputs();
  61338. return _this;
  61339. }
  61340. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  61341. //-- Begin properties for backward compatibility for inputs
  61342. get: function () {
  61343. var touch = this.inputs.attached["touch"];
  61344. if (touch)
  61345. return touch.touchAngularSensibility;
  61346. return 0;
  61347. },
  61348. set: function (value) {
  61349. var touch = this.inputs.attached["touch"];
  61350. if (touch)
  61351. touch.touchAngularSensibility = value;
  61352. },
  61353. enumerable: true,
  61354. configurable: true
  61355. });
  61356. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  61357. get: function () {
  61358. var touch = this.inputs.attached["touch"];
  61359. if (touch)
  61360. return touch.touchMoveSensibility;
  61361. return 0;
  61362. },
  61363. set: function (value) {
  61364. var touch = this.inputs.attached["touch"];
  61365. if (touch)
  61366. touch.touchMoveSensibility = value;
  61367. },
  61368. enumerable: true,
  61369. configurable: true
  61370. });
  61371. TouchCamera.prototype.getClassName = function () {
  61372. return "TouchCamera";
  61373. };
  61374. TouchCamera.prototype._setupInputs = function () {
  61375. var mouse = this.inputs.attached["mouse"];
  61376. if (mouse) {
  61377. mouse.touchEnabled = false;
  61378. }
  61379. };
  61380. return TouchCamera;
  61381. }(BABYLON.FreeCamera));
  61382. BABYLON.TouchCamera = TouchCamera;
  61383. })(BABYLON || (BABYLON = {}));
  61384. //# sourceMappingURL=babylon.touchCamera.js.map
  61385. var BABYLON;
  61386. (function (BABYLON) {
  61387. var ProceduralTexture = /** @class */ (function (_super) {
  61388. __extends(ProceduralTexture, _super);
  61389. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  61390. if (fallbackTexture === void 0) { fallbackTexture = null; }
  61391. if (generateMipMaps === void 0) { generateMipMaps = true; }
  61392. if (isCube === void 0) { isCube = false; }
  61393. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  61394. _this.isCube = isCube;
  61395. _this.isEnabled = true;
  61396. _this._currentRefreshId = -1;
  61397. _this._refreshRate = 1;
  61398. _this._vertexBuffers = {};
  61399. _this._uniforms = new Array();
  61400. _this._samplers = new Array();
  61401. _this._textures = {};
  61402. _this._floats = {};
  61403. _this._floatsArrays = {};
  61404. _this._colors3 = {};
  61405. _this._colors4 = {};
  61406. _this._vectors2 = {};
  61407. _this._vectors3 = {};
  61408. _this._matrices = {};
  61409. _this._fallbackTextureUsed = false;
  61410. scene._proceduralTextures.push(_this);
  61411. _this._engine = scene.getEngine();
  61412. _this.name = name;
  61413. _this.isRenderTarget = true;
  61414. _this._size = size;
  61415. _this._generateMipMaps = generateMipMaps;
  61416. _this.setFragment(fragment);
  61417. _this._fallbackTexture = fallbackTexture;
  61418. if (isCube) {
  61419. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  61420. _this.setFloat("face", 0);
  61421. }
  61422. else {
  61423. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  61424. }
  61425. // VBO
  61426. var vertices = [];
  61427. vertices.push(1, 1);
  61428. vertices.push(-1, 1);
  61429. vertices.push(-1, -1);
  61430. vertices.push(1, -1);
  61431. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  61432. _this._createIndexBuffer();
  61433. return _this;
  61434. }
  61435. ProceduralTexture.prototype._createIndexBuffer = function () {
  61436. var engine = this._engine;
  61437. // Indices
  61438. var indices = [];
  61439. indices.push(0);
  61440. indices.push(1);
  61441. indices.push(2);
  61442. indices.push(0);
  61443. indices.push(2);
  61444. indices.push(3);
  61445. this._indexBuffer = engine.createIndexBuffer(indices);
  61446. };
  61447. ProceduralTexture.prototype._rebuild = function () {
  61448. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61449. if (vb) {
  61450. vb._rebuild();
  61451. }
  61452. this._createIndexBuffer();
  61453. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  61454. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  61455. }
  61456. };
  61457. ProceduralTexture.prototype.reset = function () {
  61458. if (this._effect === undefined) {
  61459. return;
  61460. }
  61461. var engine = this._engine;
  61462. engine._releaseEffect(this._effect);
  61463. };
  61464. ProceduralTexture.prototype.isReady = function () {
  61465. var _this = this;
  61466. var engine = this._engine;
  61467. var shaders;
  61468. if (!this._fragment) {
  61469. return false;
  61470. }
  61471. if (this._fallbackTextureUsed) {
  61472. return true;
  61473. }
  61474. if (this._fragment.fragmentElement !== undefined) {
  61475. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  61476. }
  61477. else {
  61478. shaders = { vertex: "procedural", fragment: this._fragment };
  61479. }
  61480. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  61481. _this.releaseInternalTexture();
  61482. if (_this._fallbackTexture) {
  61483. _this._texture = _this._fallbackTexture._texture;
  61484. if (_this._texture) {
  61485. _this._texture.incrementReferences();
  61486. }
  61487. }
  61488. _this._fallbackTextureUsed = true;
  61489. });
  61490. return this._effect.isReady();
  61491. };
  61492. ProceduralTexture.prototype.resetRefreshCounter = function () {
  61493. this._currentRefreshId = -1;
  61494. };
  61495. ProceduralTexture.prototype.setFragment = function (fragment) {
  61496. this._fragment = fragment;
  61497. };
  61498. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  61499. get: function () {
  61500. return this._refreshRate;
  61501. },
  61502. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  61503. set: function (value) {
  61504. this._refreshRate = value;
  61505. this.resetRefreshCounter();
  61506. },
  61507. enumerable: true,
  61508. configurable: true
  61509. });
  61510. ProceduralTexture.prototype._shouldRender = function () {
  61511. if (!this.isEnabled || !this.isReady() || !this._texture) {
  61512. return false;
  61513. }
  61514. if (this._fallbackTextureUsed) {
  61515. return false;
  61516. }
  61517. if (this._currentRefreshId === -1) {
  61518. this._currentRefreshId = 1;
  61519. return true;
  61520. }
  61521. if (this.refreshRate === this._currentRefreshId) {
  61522. this._currentRefreshId = 1;
  61523. return true;
  61524. }
  61525. this._currentRefreshId++;
  61526. return false;
  61527. };
  61528. ProceduralTexture.prototype.getRenderSize = function () {
  61529. return this._size;
  61530. };
  61531. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  61532. if (this._fallbackTextureUsed) {
  61533. return;
  61534. }
  61535. this.releaseInternalTexture();
  61536. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  61537. };
  61538. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  61539. if (this._uniforms.indexOf(uniformName) === -1) {
  61540. this._uniforms.push(uniformName);
  61541. }
  61542. };
  61543. ProceduralTexture.prototype.setTexture = function (name, texture) {
  61544. if (this._samplers.indexOf(name) === -1) {
  61545. this._samplers.push(name);
  61546. }
  61547. this._textures[name] = texture;
  61548. return this;
  61549. };
  61550. ProceduralTexture.prototype.setFloat = function (name, value) {
  61551. this._checkUniform(name);
  61552. this._floats[name] = value;
  61553. return this;
  61554. };
  61555. ProceduralTexture.prototype.setFloats = function (name, value) {
  61556. this._checkUniform(name);
  61557. this._floatsArrays[name] = value;
  61558. return this;
  61559. };
  61560. ProceduralTexture.prototype.setColor3 = function (name, value) {
  61561. this._checkUniform(name);
  61562. this._colors3[name] = value;
  61563. return this;
  61564. };
  61565. ProceduralTexture.prototype.setColor4 = function (name, value) {
  61566. this._checkUniform(name);
  61567. this._colors4[name] = value;
  61568. return this;
  61569. };
  61570. ProceduralTexture.prototype.setVector2 = function (name, value) {
  61571. this._checkUniform(name);
  61572. this._vectors2[name] = value;
  61573. return this;
  61574. };
  61575. ProceduralTexture.prototype.setVector3 = function (name, value) {
  61576. this._checkUniform(name);
  61577. this._vectors3[name] = value;
  61578. return this;
  61579. };
  61580. ProceduralTexture.prototype.setMatrix = function (name, value) {
  61581. this._checkUniform(name);
  61582. this._matrices[name] = value;
  61583. return this;
  61584. };
  61585. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  61586. var scene = this.getScene();
  61587. if (!scene) {
  61588. return;
  61589. }
  61590. var engine = this._engine;
  61591. // Render
  61592. engine.enableEffect(this._effect);
  61593. engine.setState(false);
  61594. // Texture
  61595. for (var name in this._textures) {
  61596. this._effect.setTexture(name, this._textures[name]);
  61597. }
  61598. // Float
  61599. for (name in this._floats) {
  61600. this._effect.setFloat(name, this._floats[name]);
  61601. }
  61602. // Floats
  61603. for (name in this._floatsArrays) {
  61604. this._effect.setArray(name, this._floatsArrays[name]);
  61605. }
  61606. // Color3
  61607. for (name in this._colors3) {
  61608. this._effect.setColor3(name, this._colors3[name]);
  61609. }
  61610. // Color4
  61611. for (name in this._colors4) {
  61612. var color = this._colors4[name];
  61613. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  61614. }
  61615. // Vector2
  61616. for (name in this._vectors2) {
  61617. this._effect.setVector2(name, this._vectors2[name]);
  61618. }
  61619. // Vector3
  61620. for (name in this._vectors3) {
  61621. this._effect.setVector3(name, this._vectors3[name]);
  61622. }
  61623. // Matrix
  61624. for (name in this._matrices) {
  61625. this._effect.setMatrix(name, this._matrices[name]);
  61626. }
  61627. if (!this._texture) {
  61628. return;
  61629. }
  61630. if (this.isCube) {
  61631. for (var face = 0; face < 6; face++) {
  61632. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  61633. // VBOs
  61634. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  61635. this._effect.setFloat("face", face);
  61636. // Clear
  61637. engine.clear(scene.clearColor, true, true, true);
  61638. // Draw order
  61639. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  61640. // Mipmaps
  61641. if (face === 5) {
  61642. engine.generateMipMapsForCubemap(this._texture);
  61643. }
  61644. }
  61645. }
  61646. else {
  61647. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  61648. // VBOs
  61649. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  61650. // Clear
  61651. engine.clear(scene.clearColor, true, true, true);
  61652. // Draw order
  61653. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  61654. }
  61655. // Unbind
  61656. engine.unBindFramebuffer(this._texture, this.isCube);
  61657. if (this.onGenerated) {
  61658. this.onGenerated();
  61659. }
  61660. };
  61661. ProceduralTexture.prototype.clone = function () {
  61662. var textureSize = this.getSize();
  61663. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  61664. // Base texture
  61665. newTexture.hasAlpha = this.hasAlpha;
  61666. newTexture.level = this.level;
  61667. // RenderTarget Texture
  61668. newTexture.coordinatesMode = this.coordinatesMode;
  61669. return newTexture;
  61670. };
  61671. ProceduralTexture.prototype.dispose = function () {
  61672. var scene = this.getScene();
  61673. if (!scene) {
  61674. return;
  61675. }
  61676. var index = scene._proceduralTextures.indexOf(this);
  61677. if (index >= 0) {
  61678. scene._proceduralTextures.splice(index, 1);
  61679. }
  61680. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61681. if (vertexBuffer) {
  61682. vertexBuffer.dispose();
  61683. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  61684. }
  61685. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  61686. this._indexBuffer = null;
  61687. }
  61688. _super.prototype.dispose.call(this);
  61689. };
  61690. return ProceduralTexture;
  61691. }(BABYLON.Texture));
  61692. BABYLON.ProceduralTexture = ProceduralTexture;
  61693. })(BABYLON || (BABYLON = {}));
  61694. //# sourceMappingURL=babylon.proceduralTexture.js.map
  61695. var BABYLON;
  61696. (function (BABYLON) {
  61697. var CustomProceduralTexture = /** @class */ (function (_super) {
  61698. __extends(CustomProceduralTexture, _super);
  61699. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  61700. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  61701. _this._animate = true;
  61702. _this._time = 0;
  61703. _this._texturePath = texturePath;
  61704. //Try to load json
  61705. _this.loadJson(texturePath);
  61706. _this.refreshRate = 1;
  61707. return _this;
  61708. }
  61709. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  61710. var _this = this;
  61711. var noConfigFile = function () {
  61712. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  61713. try {
  61714. _this.setFragment(_this._texturePath);
  61715. }
  61716. catch (ex) {
  61717. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  61718. }
  61719. };
  61720. var configFileUrl = jsonUrl + "/config.json";
  61721. var xhr = new XMLHttpRequest();
  61722. xhr.open("GET", configFileUrl, true);
  61723. xhr.addEventListener("load", function () {
  61724. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  61725. try {
  61726. _this._config = JSON.parse(xhr.response);
  61727. _this.updateShaderUniforms();
  61728. _this.updateTextures();
  61729. _this.setFragment(_this._texturePath + "/custom");
  61730. _this._animate = _this._config.animate;
  61731. _this.refreshRate = _this._config.refreshrate;
  61732. }
  61733. catch (ex) {
  61734. noConfigFile();
  61735. }
  61736. }
  61737. else {
  61738. noConfigFile();
  61739. }
  61740. }, false);
  61741. xhr.addEventListener("error", function () {
  61742. noConfigFile();
  61743. }, false);
  61744. try {
  61745. xhr.send();
  61746. }
  61747. catch (ex) {
  61748. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  61749. }
  61750. };
  61751. CustomProceduralTexture.prototype.isReady = function () {
  61752. if (!_super.prototype.isReady.call(this)) {
  61753. return false;
  61754. }
  61755. for (var name in this._textures) {
  61756. var texture = this._textures[name];
  61757. if (!texture.isReady()) {
  61758. return false;
  61759. }
  61760. }
  61761. return true;
  61762. };
  61763. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  61764. var scene = this.getScene();
  61765. if (this._animate && scene) {
  61766. this._time += scene.getAnimationRatio() * 0.03;
  61767. this.updateShaderUniforms();
  61768. }
  61769. _super.prototype.render.call(this, useCameraPostProcess);
  61770. };
  61771. CustomProceduralTexture.prototype.updateTextures = function () {
  61772. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  61773. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  61774. }
  61775. };
  61776. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  61777. if (this._config) {
  61778. for (var j = 0; j < this._config.uniforms.length; j++) {
  61779. var uniform = this._config.uniforms[j];
  61780. switch (uniform.type) {
  61781. case "float":
  61782. this.setFloat(uniform.name, uniform.value);
  61783. break;
  61784. case "color3":
  61785. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  61786. break;
  61787. case "color4":
  61788. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  61789. break;
  61790. case "vector2":
  61791. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  61792. break;
  61793. case "vector3":
  61794. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  61795. break;
  61796. }
  61797. }
  61798. }
  61799. this.setFloat("time", this._time);
  61800. };
  61801. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  61802. get: function () {
  61803. return this._animate;
  61804. },
  61805. set: function (value) {
  61806. this._animate = value;
  61807. },
  61808. enumerable: true,
  61809. configurable: true
  61810. });
  61811. return CustomProceduralTexture;
  61812. }(BABYLON.ProceduralTexture));
  61813. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  61814. })(BABYLON || (BABYLON = {}));
  61815. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  61816. var BABYLON;
  61817. (function (BABYLON) {
  61818. var FreeCameraGamepadInput = /** @class */ (function () {
  61819. function FreeCameraGamepadInput() {
  61820. this.gamepadAngularSensibility = 200;
  61821. this.gamepadMoveSensibility = 40;
  61822. // private members
  61823. this._cameraTransform = BABYLON.Matrix.Identity();
  61824. this._deltaTransform = BABYLON.Vector3.Zero();
  61825. this._vector3 = BABYLON.Vector3.Zero();
  61826. this._vector2 = BABYLON.Vector2.Zero();
  61827. }
  61828. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  61829. var _this = this;
  61830. var manager = this.camera.getScene().gamepadManager;
  61831. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  61832. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  61833. // prioritize XBOX gamepads.
  61834. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  61835. _this.gamepad = gamepad;
  61836. }
  61837. }
  61838. });
  61839. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  61840. if (_this.gamepad === gamepad) {
  61841. _this.gamepad = null;
  61842. }
  61843. });
  61844. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  61845. };
  61846. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  61847. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  61848. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  61849. this.gamepad = null;
  61850. };
  61851. FreeCameraGamepadInput.prototype.checkInputs = function () {
  61852. if (this.gamepad && this.gamepad.leftStick) {
  61853. var camera = this.camera;
  61854. var LSValues = this.gamepad.leftStick;
  61855. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  61856. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  61857. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  61858. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  61859. var RSValues = this.gamepad.rightStick;
  61860. if (RSValues) {
  61861. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  61862. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  61863. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  61864. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  61865. }
  61866. else {
  61867. RSValues = { x: 0, y: 0 };
  61868. }
  61869. if (!camera.rotationQuaternion) {
  61870. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  61871. }
  61872. else {
  61873. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  61874. }
  61875. var speed = camera._computeLocalCameraSpeed() * 50.0;
  61876. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  61877. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  61878. camera.cameraDirection.addInPlace(this._deltaTransform);
  61879. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  61880. camera.cameraRotation.addInPlace(this._vector2);
  61881. }
  61882. };
  61883. FreeCameraGamepadInput.prototype.getClassName = function () {
  61884. return "FreeCameraGamepadInput";
  61885. };
  61886. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  61887. return "gamepad";
  61888. };
  61889. __decorate([
  61890. BABYLON.serialize()
  61891. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  61892. __decorate([
  61893. BABYLON.serialize()
  61894. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  61895. return FreeCameraGamepadInput;
  61896. }());
  61897. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  61898. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  61899. })(BABYLON || (BABYLON = {}));
  61900. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  61901. var BABYLON;
  61902. (function (BABYLON) {
  61903. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  61904. function ArcRotateCameraGamepadInput() {
  61905. this.gamepadRotationSensibility = 80;
  61906. this.gamepadMoveSensibility = 40;
  61907. }
  61908. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  61909. var _this = this;
  61910. var manager = this.camera.getScene().gamepadManager;
  61911. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  61912. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  61913. // prioritize XBOX gamepads.
  61914. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  61915. _this.gamepad = gamepad;
  61916. }
  61917. }
  61918. });
  61919. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  61920. if (_this.gamepad === gamepad) {
  61921. _this.gamepad = null;
  61922. }
  61923. });
  61924. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  61925. };
  61926. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  61927. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  61928. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  61929. this.gamepad = null;
  61930. };
  61931. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  61932. if (this.gamepad) {
  61933. var camera = this.camera;
  61934. var RSValues = this.gamepad.rightStick;
  61935. if (RSValues) {
  61936. if (RSValues.x != 0) {
  61937. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  61938. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  61939. camera.inertialAlphaOffset += normalizedRX;
  61940. }
  61941. }
  61942. if (RSValues.y != 0) {
  61943. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  61944. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  61945. camera.inertialBetaOffset += normalizedRY;
  61946. }
  61947. }
  61948. }
  61949. var LSValues = this.gamepad.leftStick;
  61950. if (LSValues && LSValues.y != 0) {
  61951. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  61952. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  61953. this.camera.inertialRadiusOffset -= normalizedLY;
  61954. }
  61955. }
  61956. }
  61957. };
  61958. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  61959. return "ArcRotateCameraGamepadInput";
  61960. };
  61961. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  61962. return "gamepad";
  61963. };
  61964. __decorate([
  61965. BABYLON.serialize()
  61966. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  61967. __decorate([
  61968. BABYLON.serialize()
  61969. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  61970. return ArcRotateCameraGamepadInput;
  61971. }());
  61972. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  61973. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  61974. })(BABYLON || (BABYLON = {}));
  61975. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  61976. var BABYLON;
  61977. (function (BABYLON) {
  61978. var GamepadManager = /** @class */ (function () {
  61979. function GamepadManager(_scene) {
  61980. var _this = this;
  61981. this._scene = _scene;
  61982. this._babylonGamepads = [];
  61983. this._oneGamepadConnected = false;
  61984. this._isMonitoring = false;
  61985. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  61986. if (!BABYLON.Tools.IsWindowObjectExist()) {
  61987. this._gamepadEventSupported = false;
  61988. }
  61989. else {
  61990. this._gamepadEventSupported = 'GamepadEvent' in window;
  61991. this._gamepadSupport = (navigator.getGamepads ||
  61992. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  61993. }
  61994. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  61995. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  61996. for (var i in _this._babylonGamepads) {
  61997. var gamepad = _this._babylonGamepads[i];
  61998. if (gamepad && gamepad._isConnected) {
  61999. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  62000. }
  62001. }
  62002. });
  62003. this._onGamepadConnectedEvent = function (evt) {
  62004. var gamepad = evt.gamepad;
  62005. if (gamepad.index in _this._babylonGamepads) {
  62006. if (_this._babylonGamepads[gamepad.index].isConnected) {
  62007. return;
  62008. }
  62009. }
  62010. var newGamepad;
  62011. if (_this._babylonGamepads[gamepad.index]) {
  62012. newGamepad = _this._babylonGamepads[gamepad.index];
  62013. newGamepad.browserGamepad = gamepad;
  62014. newGamepad._isConnected = true;
  62015. }
  62016. else {
  62017. newGamepad = _this._addNewGamepad(gamepad);
  62018. }
  62019. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  62020. _this._startMonitoringGamepads();
  62021. };
  62022. this._onGamepadDisconnectedEvent = function (evt) {
  62023. var gamepad = evt.gamepad;
  62024. // Remove the gamepad from the list of gamepads to monitor.
  62025. for (var i in _this._babylonGamepads) {
  62026. if (_this._babylonGamepads[i].index === gamepad.index) {
  62027. var disconnectedGamepad = _this._babylonGamepads[i];
  62028. disconnectedGamepad._isConnected = false;
  62029. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  62030. break;
  62031. }
  62032. }
  62033. };
  62034. if (this._gamepadSupport) {
  62035. //first add already-connected gamepads
  62036. this._updateGamepadObjects();
  62037. if (this._babylonGamepads.length) {
  62038. this._startMonitoringGamepads();
  62039. }
  62040. // Checking if the gamepad connected event is supported (like in Firefox)
  62041. if (this._gamepadEventSupported) {
  62042. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  62043. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  62044. }
  62045. else {
  62046. this._startMonitoringGamepads();
  62047. }
  62048. }
  62049. }
  62050. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  62051. get: function () {
  62052. return this._babylonGamepads;
  62053. },
  62054. enumerable: true,
  62055. configurable: true
  62056. });
  62057. GamepadManager.prototype.getGamepadByType = function (type) {
  62058. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  62059. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  62060. var gamepad = _a[_i];
  62061. if (gamepad && gamepad.type === type) {
  62062. return gamepad;
  62063. }
  62064. }
  62065. return null;
  62066. };
  62067. GamepadManager.prototype.dispose = function () {
  62068. if (this._gamepadEventSupported) {
  62069. if (this._onGamepadConnectedEvent) {
  62070. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  62071. }
  62072. if (this._onGamepadDisconnectedEvent) {
  62073. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  62074. }
  62075. this._onGamepadConnectedEvent = null;
  62076. this._onGamepadDisconnectedEvent = null;
  62077. }
  62078. this._babylonGamepads.forEach(function (gamepad) {
  62079. gamepad.dispose();
  62080. });
  62081. this.onGamepadConnectedObservable.clear();
  62082. this.onGamepadDisconnectedObservable.clear();
  62083. this._oneGamepadConnected = false;
  62084. this._stopMonitoringGamepads();
  62085. this._babylonGamepads = [];
  62086. };
  62087. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  62088. if (!this._oneGamepadConnected) {
  62089. this._oneGamepadConnected = true;
  62090. }
  62091. var newGamepad;
  62092. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  62093. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  62094. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  62095. }
  62096. else if (gamepad.pose) {
  62097. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  62098. }
  62099. else {
  62100. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  62101. }
  62102. this._babylonGamepads[newGamepad.index] = newGamepad;
  62103. return newGamepad;
  62104. };
  62105. GamepadManager.prototype._startMonitoringGamepads = function () {
  62106. if (!this._isMonitoring) {
  62107. this._isMonitoring = true;
  62108. //back-comp
  62109. if (!this._scene) {
  62110. this._checkGamepadsStatus();
  62111. }
  62112. }
  62113. };
  62114. GamepadManager.prototype._stopMonitoringGamepads = function () {
  62115. this._isMonitoring = false;
  62116. };
  62117. GamepadManager.prototype._checkGamepadsStatus = function () {
  62118. var _this = this;
  62119. // Hack to be compatible Chrome
  62120. this._updateGamepadObjects();
  62121. for (var i in this._babylonGamepads) {
  62122. var gamepad = this._babylonGamepads[i];
  62123. if (!gamepad || !gamepad.isConnected) {
  62124. continue;
  62125. }
  62126. gamepad.update();
  62127. }
  62128. if (this._isMonitoring && !this._scene) {
  62129. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  62130. }
  62131. };
  62132. // This function is called only on Chrome, which does not properly support
  62133. // connection/disconnection events and forces you to recopy again the gamepad object
  62134. GamepadManager.prototype._updateGamepadObjects = function () {
  62135. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  62136. for (var i = 0; i < gamepads.length; i++) {
  62137. if (gamepads[i]) {
  62138. if (!this._babylonGamepads[gamepads[i].index]) {
  62139. var newGamepad = this._addNewGamepad(gamepads[i]);
  62140. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  62141. }
  62142. else {
  62143. // Forced to copy again this object for Chrome for unknown reason
  62144. this._babylonGamepads[i].browserGamepad = gamepads[i];
  62145. if (!this._babylonGamepads[i].isConnected) {
  62146. this._babylonGamepads[i]._isConnected = true;
  62147. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  62148. }
  62149. }
  62150. }
  62151. }
  62152. };
  62153. return GamepadManager;
  62154. }());
  62155. BABYLON.GamepadManager = GamepadManager;
  62156. })(BABYLON || (BABYLON = {}));
  62157. //# sourceMappingURL=babylon.gamepadManager.js.map
  62158. var BABYLON;
  62159. (function (BABYLON) {
  62160. var StickValues = /** @class */ (function () {
  62161. function StickValues(x, y) {
  62162. this.x = x;
  62163. this.y = y;
  62164. }
  62165. return StickValues;
  62166. }());
  62167. BABYLON.StickValues = StickValues;
  62168. var Gamepad = /** @class */ (function () {
  62169. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  62170. if (leftStickX === void 0) { leftStickX = 0; }
  62171. if (leftStickY === void 0) { leftStickY = 1; }
  62172. if (rightStickX === void 0) { rightStickX = 2; }
  62173. if (rightStickY === void 0) { rightStickY = 3; }
  62174. this.id = id;
  62175. this.index = index;
  62176. this.browserGamepad = browserGamepad;
  62177. this._isConnected = true;
  62178. this._invertLeftStickY = false;
  62179. this.type = Gamepad.GAMEPAD;
  62180. this._leftStickAxisX = leftStickX;
  62181. this._leftStickAxisY = leftStickY;
  62182. this._rightStickAxisX = rightStickX;
  62183. this._rightStickAxisY = rightStickY;
  62184. if (this.browserGamepad.axes.length >= 2) {
  62185. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  62186. }
  62187. if (this.browserGamepad.axes.length >= 4) {
  62188. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  62189. }
  62190. }
  62191. Object.defineProperty(Gamepad.prototype, "isConnected", {
  62192. get: function () {
  62193. return this._isConnected;
  62194. },
  62195. enumerable: true,
  62196. configurable: true
  62197. });
  62198. Gamepad.prototype.onleftstickchanged = function (callback) {
  62199. this._onleftstickchanged = callback;
  62200. };
  62201. Gamepad.prototype.onrightstickchanged = function (callback) {
  62202. this._onrightstickchanged = callback;
  62203. };
  62204. Object.defineProperty(Gamepad.prototype, "leftStick", {
  62205. get: function () {
  62206. return this._leftStick;
  62207. },
  62208. set: function (newValues) {
  62209. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  62210. this._onleftstickchanged(newValues);
  62211. }
  62212. this._leftStick = newValues;
  62213. },
  62214. enumerable: true,
  62215. configurable: true
  62216. });
  62217. Object.defineProperty(Gamepad.prototype, "rightStick", {
  62218. get: function () {
  62219. return this._rightStick;
  62220. },
  62221. set: function (newValues) {
  62222. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  62223. this._onrightstickchanged(newValues);
  62224. }
  62225. this._rightStick = newValues;
  62226. },
  62227. enumerable: true,
  62228. configurable: true
  62229. });
  62230. Gamepad.prototype.update = function () {
  62231. if (this._leftStick) {
  62232. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  62233. if (this._invertLeftStickY) {
  62234. this.leftStick.y *= -1;
  62235. }
  62236. }
  62237. if (this._rightStick) {
  62238. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  62239. }
  62240. };
  62241. Gamepad.prototype.dispose = function () {
  62242. };
  62243. Gamepad.GAMEPAD = 0;
  62244. Gamepad.GENERIC = 1;
  62245. Gamepad.XBOX = 2;
  62246. Gamepad.POSE_ENABLED = 3;
  62247. return Gamepad;
  62248. }());
  62249. BABYLON.Gamepad = Gamepad;
  62250. var GenericPad = /** @class */ (function (_super) {
  62251. __extends(GenericPad, _super);
  62252. function GenericPad(id, index, browserGamepad) {
  62253. var _this = _super.call(this, id, index, browserGamepad) || this;
  62254. _this.onButtonDownObservable = new BABYLON.Observable();
  62255. _this.onButtonUpObservable = new BABYLON.Observable();
  62256. _this.type = Gamepad.GENERIC;
  62257. _this._buttons = new Array(browserGamepad.buttons.length);
  62258. return _this;
  62259. }
  62260. GenericPad.prototype.onbuttondown = function (callback) {
  62261. this._onbuttondown = callback;
  62262. };
  62263. GenericPad.prototype.onbuttonup = function (callback) {
  62264. this._onbuttonup = callback;
  62265. };
  62266. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  62267. if (newValue !== currentValue) {
  62268. if (newValue === 1) {
  62269. if (this._onbuttondown) {
  62270. this._onbuttondown(buttonIndex);
  62271. }
  62272. this.onButtonDownObservable.notifyObservers(buttonIndex);
  62273. }
  62274. if (newValue === 0) {
  62275. if (this._onbuttonup) {
  62276. this._onbuttonup(buttonIndex);
  62277. }
  62278. this.onButtonUpObservable.notifyObservers(buttonIndex);
  62279. }
  62280. }
  62281. return newValue;
  62282. };
  62283. GenericPad.prototype.update = function () {
  62284. _super.prototype.update.call(this);
  62285. for (var index = 0; index < this._buttons.length; index++) {
  62286. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  62287. }
  62288. };
  62289. GenericPad.prototype.dispose = function () {
  62290. _super.prototype.dispose.call(this);
  62291. this.onButtonDownObservable.clear();
  62292. this.onButtonUpObservable.clear();
  62293. };
  62294. return GenericPad;
  62295. }(Gamepad));
  62296. BABYLON.GenericPad = GenericPad;
  62297. })(BABYLON || (BABYLON = {}));
  62298. //# sourceMappingURL=babylon.gamepad.js.map
  62299. var BABYLON;
  62300. (function (BABYLON) {
  62301. var Xbox360Button;
  62302. (function (Xbox360Button) {
  62303. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  62304. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  62305. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  62306. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  62307. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  62308. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  62309. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  62310. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  62311. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  62312. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  62313. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  62314. var Xbox360Dpad;
  62315. (function (Xbox360Dpad) {
  62316. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  62317. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  62318. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  62319. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  62320. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  62321. var Xbox360Pad = /** @class */ (function (_super) {
  62322. __extends(Xbox360Pad, _super);
  62323. function Xbox360Pad(id, index, gamepad, xboxOne) {
  62324. if (xboxOne === void 0) { xboxOne = false; }
  62325. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  62326. _this._leftTrigger = 0;
  62327. _this._rightTrigger = 0;
  62328. _this.onButtonDownObservable = new BABYLON.Observable();
  62329. _this.onButtonUpObservable = new BABYLON.Observable();
  62330. _this.onPadDownObservable = new BABYLON.Observable();
  62331. _this.onPadUpObservable = new BABYLON.Observable();
  62332. _this._buttonA = 0;
  62333. _this._buttonB = 0;
  62334. _this._buttonX = 0;
  62335. _this._buttonY = 0;
  62336. _this._buttonBack = 0;
  62337. _this._buttonStart = 0;
  62338. _this._buttonLB = 0;
  62339. _this._buttonRB = 0;
  62340. _this._buttonLeftStick = 0;
  62341. _this._buttonRightStick = 0;
  62342. _this._dPadUp = 0;
  62343. _this._dPadDown = 0;
  62344. _this._dPadLeft = 0;
  62345. _this._dPadRight = 0;
  62346. _this._isXboxOnePad = false;
  62347. _this.type = BABYLON.Gamepad.XBOX;
  62348. _this._isXboxOnePad = xboxOne;
  62349. return _this;
  62350. }
  62351. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  62352. this._onlefttriggerchanged = callback;
  62353. };
  62354. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  62355. this._onrighttriggerchanged = callback;
  62356. };
  62357. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  62358. get: function () {
  62359. return this._leftTrigger;
  62360. },
  62361. set: function (newValue) {
  62362. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  62363. this._onlefttriggerchanged(newValue);
  62364. }
  62365. this._leftTrigger = newValue;
  62366. },
  62367. enumerable: true,
  62368. configurable: true
  62369. });
  62370. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  62371. get: function () {
  62372. return this._rightTrigger;
  62373. },
  62374. set: function (newValue) {
  62375. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  62376. this._onrighttriggerchanged(newValue);
  62377. }
  62378. this._rightTrigger = newValue;
  62379. },
  62380. enumerable: true,
  62381. configurable: true
  62382. });
  62383. Xbox360Pad.prototype.onbuttondown = function (callback) {
  62384. this._onbuttondown = callback;
  62385. };
  62386. Xbox360Pad.prototype.onbuttonup = function (callback) {
  62387. this._onbuttonup = callback;
  62388. };
  62389. Xbox360Pad.prototype.ondpaddown = function (callback) {
  62390. this._ondpaddown = callback;
  62391. };
  62392. Xbox360Pad.prototype.ondpadup = function (callback) {
  62393. this._ondpadup = callback;
  62394. };
  62395. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  62396. if (newValue !== currentValue) {
  62397. if (newValue === 1) {
  62398. if (this._onbuttondown) {
  62399. this._onbuttondown(buttonType);
  62400. }
  62401. this.onButtonDownObservable.notifyObservers(buttonType);
  62402. }
  62403. if (newValue === 0) {
  62404. if (this._onbuttonup) {
  62405. this._onbuttonup(buttonType);
  62406. }
  62407. this.onButtonUpObservable.notifyObservers(buttonType);
  62408. }
  62409. }
  62410. return newValue;
  62411. };
  62412. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  62413. if (newValue !== currentValue) {
  62414. if (newValue === 1) {
  62415. if (this._ondpaddown) {
  62416. this._ondpaddown(buttonType);
  62417. }
  62418. this.onPadDownObservable.notifyObservers(buttonType);
  62419. }
  62420. if (newValue === 0) {
  62421. if (this._ondpadup) {
  62422. this._ondpadup(buttonType);
  62423. }
  62424. this.onPadUpObservable.notifyObservers(buttonType);
  62425. }
  62426. }
  62427. return newValue;
  62428. };
  62429. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  62430. get: function () {
  62431. return this._buttonA;
  62432. },
  62433. set: function (value) {
  62434. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  62435. },
  62436. enumerable: true,
  62437. configurable: true
  62438. });
  62439. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  62440. get: function () {
  62441. return this._buttonB;
  62442. },
  62443. set: function (value) {
  62444. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  62445. },
  62446. enumerable: true,
  62447. configurable: true
  62448. });
  62449. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  62450. get: function () {
  62451. return this._buttonX;
  62452. },
  62453. set: function (value) {
  62454. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  62455. },
  62456. enumerable: true,
  62457. configurable: true
  62458. });
  62459. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  62460. get: function () {
  62461. return this._buttonY;
  62462. },
  62463. set: function (value) {
  62464. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  62465. },
  62466. enumerable: true,
  62467. configurable: true
  62468. });
  62469. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  62470. get: function () {
  62471. return this._buttonStart;
  62472. },
  62473. set: function (value) {
  62474. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  62475. },
  62476. enumerable: true,
  62477. configurable: true
  62478. });
  62479. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  62480. get: function () {
  62481. return this._buttonBack;
  62482. },
  62483. set: function (value) {
  62484. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  62485. },
  62486. enumerable: true,
  62487. configurable: true
  62488. });
  62489. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  62490. get: function () {
  62491. return this._buttonLB;
  62492. },
  62493. set: function (value) {
  62494. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  62495. },
  62496. enumerable: true,
  62497. configurable: true
  62498. });
  62499. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  62500. get: function () {
  62501. return this._buttonRB;
  62502. },
  62503. set: function (value) {
  62504. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  62505. },
  62506. enumerable: true,
  62507. configurable: true
  62508. });
  62509. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  62510. get: function () {
  62511. return this._buttonLeftStick;
  62512. },
  62513. set: function (value) {
  62514. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  62515. },
  62516. enumerable: true,
  62517. configurable: true
  62518. });
  62519. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  62520. get: function () {
  62521. return this._buttonRightStick;
  62522. },
  62523. set: function (value) {
  62524. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  62525. },
  62526. enumerable: true,
  62527. configurable: true
  62528. });
  62529. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  62530. get: function () {
  62531. return this._dPadUp;
  62532. },
  62533. set: function (value) {
  62534. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  62535. },
  62536. enumerable: true,
  62537. configurable: true
  62538. });
  62539. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  62540. get: function () {
  62541. return this._dPadDown;
  62542. },
  62543. set: function (value) {
  62544. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  62545. },
  62546. enumerable: true,
  62547. configurable: true
  62548. });
  62549. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  62550. get: function () {
  62551. return this._dPadLeft;
  62552. },
  62553. set: function (value) {
  62554. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  62555. },
  62556. enumerable: true,
  62557. configurable: true
  62558. });
  62559. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  62560. get: function () {
  62561. return this._dPadRight;
  62562. },
  62563. set: function (value) {
  62564. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  62565. },
  62566. enumerable: true,
  62567. configurable: true
  62568. });
  62569. Xbox360Pad.prototype.update = function () {
  62570. _super.prototype.update.call(this);
  62571. if (this._isXboxOnePad) {
  62572. this.buttonA = this.browserGamepad.buttons[0].value;
  62573. this.buttonB = this.browserGamepad.buttons[1].value;
  62574. this.buttonX = this.browserGamepad.buttons[2].value;
  62575. this.buttonY = this.browserGamepad.buttons[3].value;
  62576. this.buttonLB = this.browserGamepad.buttons[4].value;
  62577. this.buttonRB = this.browserGamepad.buttons[5].value;
  62578. this.leftTrigger = this.browserGamepad.axes[2];
  62579. this.rightTrigger = this.browserGamepad.axes[5];
  62580. this.buttonBack = this.browserGamepad.buttons[9].value;
  62581. this.buttonStart = this.browserGamepad.buttons[8].value;
  62582. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  62583. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  62584. this.dPadUp = this.browserGamepad.buttons[11].value;
  62585. this.dPadDown = this.browserGamepad.buttons[12].value;
  62586. this.dPadLeft = this.browserGamepad.buttons[13].value;
  62587. this.dPadRight = this.browserGamepad.buttons[14].value;
  62588. }
  62589. else {
  62590. this.buttonA = this.browserGamepad.buttons[0].value;
  62591. this.buttonB = this.browserGamepad.buttons[1].value;
  62592. this.buttonX = this.browserGamepad.buttons[2].value;
  62593. this.buttonY = this.browserGamepad.buttons[3].value;
  62594. this.buttonLB = this.browserGamepad.buttons[4].value;
  62595. this.buttonRB = this.browserGamepad.buttons[5].value;
  62596. this.leftTrigger = this.browserGamepad.buttons[6].value;
  62597. this.rightTrigger = this.browserGamepad.buttons[7].value;
  62598. this.buttonBack = this.browserGamepad.buttons[8].value;
  62599. this.buttonStart = this.browserGamepad.buttons[9].value;
  62600. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  62601. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  62602. this.dPadUp = this.browserGamepad.buttons[12].value;
  62603. this.dPadDown = this.browserGamepad.buttons[13].value;
  62604. this.dPadLeft = this.browserGamepad.buttons[14].value;
  62605. this.dPadRight = this.browserGamepad.buttons[15].value;
  62606. }
  62607. };
  62608. Xbox360Pad.prototype.dispose = function () {
  62609. _super.prototype.dispose.call(this);
  62610. this.onButtonDownObservable.clear();
  62611. this.onButtonUpObservable.clear();
  62612. this.onPadDownObservable.clear();
  62613. this.onPadUpObservable.clear();
  62614. };
  62615. return Xbox360Pad;
  62616. }(BABYLON.Gamepad));
  62617. BABYLON.Xbox360Pad = Xbox360Pad;
  62618. })(BABYLON || (BABYLON = {}));
  62619. //# sourceMappingURL=babylon.xboxGamepad.js.map
  62620. var BABYLON;
  62621. (function (BABYLON) {
  62622. var PoseEnabledControllerType;
  62623. (function (PoseEnabledControllerType) {
  62624. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  62625. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  62626. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  62627. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  62628. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  62629. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  62630. var PoseEnabledControllerHelper = /** @class */ (function () {
  62631. function PoseEnabledControllerHelper() {
  62632. }
  62633. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  62634. // Oculus Touch
  62635. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  62636. return new BABYLON.OculusTouchController(vrGamepad);
  62637. }
  62638. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  62639. return new BABYLON.WindowsMotionController(vrGamepad);
  62640. }
  62641. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  62642. return new BABYLON.ViveController(vrGamepad);
  62643. }
  62644. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  62645. return new BABYLON.GearVRController(vrGamepad);
  62646. }
  62647. else {
  62648. return new BABYLON.GenericController(vrGamepad);
  62649. }
  62650. };
  62651. return PoseEnabledControllerHelper;
  62652. }());
  62653. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  62654. var PoseEnabledController = /** @class */ (function (_super) {
  62655. __extends(PoseEnabledController, _super);
  62656. function PoseEnabledController(browserGamepad) {
  62657. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  62658. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  62659. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  62660. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  62661. // Represents device position and rotation in babylon space
  62662. _this.devicePosition = BABYLON.Vector3.Zero();
  62663. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  62664. _this.deviceScaleFactor = 1;
  62665. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  62666. _this._deviceToWorld = BABYLON.Matrix.Identity();
  62667. _this._workingMatrix = BABYLON.Matrix.Identity();
  62668. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  62669. _this.controllerType = PoseEnabledControllerType.GENERIC;
  62670. _this.position = BABYLON.Vector3.Zero();
  62671. _this.rotationQuaternion = new BABYLON.Quaternion();
  62672. _this._calculatedPosition = BABYLON.Vector3.Zero();
  62673. _this._calculatedRotation = new BABYLON.Quaternion();
  62674. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  62675. return _this;
  62676. }
  62677. PoseEnabledController.prototype.update = function () {
  62678. _super.prototype.update.call(this);
  62679. var pose = this.browserGamepad.pose;
  62680. this.updateFromDevice(pose);
  62681. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  62682. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  62683. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  62684. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  62685. if (this._mesh) {
  62686. this._mesh.position.copyFrom(this.devicePosition);
  62687. if (this._mesh.rotationQuaternion) {
  62688. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  62689. }
  62690. }
  62691. };
  62692. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  62693. if (poseData) {
  62694. this.rawPose = poseData;
  62695. if (poseData.position) {
  62696. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  62697. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  62698. this._deviceRoomPosition.z *= -1;
  62699. }
  62700. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  62701. this._calculatedPosition.addInPlace(this.position);
  62702. }
  62703. var pose = this.rawPose;
  62704. if (poseData.orientation && pose.orientation) {
  62705. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  62706. if (this._mesh) {
  62707. if (this._mesh.getScene().useRightHandedSystem) {
  62708. this._deviceRoomRotationQuaternion.z *= -1;
  62709. this._deviceRoomRotationQuaternion.w *= -1;
  62710. }
  62711. else {
  62712. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  62713. }
  62714. }
  62715. // if the camera is set, rotate to the camera's rotation
  62716. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  62717. }
  62718. }
  62719. };
  62720. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  62721. if (this._mesh) {
  62722. this._mesh.parent = null;
  62723. }
  62724. this._mesh = mesh;
  62725. if (this._poseControlledCamera) {
  62726. this._mesh.parent = this._poseControlledCamera;
  62727. }
  62728. if (!this._mesh.rotationQuaternion) {
  62729. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  62730. }
  62731. };
  62732. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  62733. this._poseControlledCamera = camera;
  62734. if (this._mesh) {
  62735. this._mesh.parent = this._poseControlledCamera;
  62736. }
  62737. };
  62738. PoseEnabledController.prototype.dispose = function () {
  62739. if (this._mesh) {
  62740. this._mesh.dispose();
  62741. }
  62742. this._mesh = null;
  62743. _super.prototype.dispose.call(this);
  62744. };
  62745. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  62746. get: function () {
  62747. return this._mesh;
  62748. },
  62749. enumerable: true,
  62750. configurable: true
  62751. });
  62752. PoseEnabledController.prototype.getForwardRay = function (length) {
  62753. if (length === void 0) { length = 100; }
  62754. if (!this.mesh) {
  62755. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  62756. }
  62757. var m = this.mesh.getWorldMatrix();
  62758. var origin = m.getTranslation();
  62759. var forward = new BABYLON.Vector3(0, 0, -1);
  62760. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  62761. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  62762. return new BABYLON.Ray(origin, direction, length);
  62763. };
  62764. return PoseEnabledController;
  62765. }(BABYLON.Gamepad));
  62766. BABYLON.PoseEnabledController = PoseEnabledController;
  62767. })(BABYLON || (BABYLON = {}));
  62768. //# sourceMappingURL=babylon.poseEnabledController.js.map
  62769. var BABYLON;
  62770. (function (BABYLON) {
  62771. var WebVRController = /** @class */ (function (_super) {
  62772. __extends(WebVRController, _super);
  62773. function WebVRController(vrGamepad) {
  62774. var _this = _super.call(this, vrGamepad) || this;
  62775. // Observables
  62776. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  62777. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  62778. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  62779. _this.onPadStateChangedObservable = new BABYLON.Observable();
  62780. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  62781. _this.pad = { x: 0, y: 0 };
  62782. // avoid GC, store state in a tmp object
  62783. _this._changes = {
  62784. pressChanged: false,
  62785. touchChanged: false,
  62786. valueChanged: false,
  62787. changed: false
  62788. };
  62789. _this._buttons = new Array(vrGamepad.buttons.length);
  62790. _this.hand = vrGamepad.hand;
  62791. return _this;
  62792. }
  62793. WebVRController.prototype.onButtonStateChange = function (callback) {
  62794. this._onButtonStateChange = callback;
  62795. };
  62796. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  62797. get: function () {
  62798. return this._defaultModel;
  62799. },
  62800. enumerable: true,
  62801. configurable: true
  62802. });
  62803. WebVRController.prototype.update = function () {
  62804. _super.prototype.update.call(this);
  62805. for (var index = 0; index < this._buttons.length; index++) {
  62806. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  62807. }
  62808. ;
  62809. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  62810. this.pad.x = this.leftStick.x;
  62811. this.pad.y = this.leftStick.y;
  62812. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  62813. }
  62814. };
  62815. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  62816. if (!newState) {
  62817. newState = {
  62818. pressed: false,
  62819. touched: false,
  62820. value: 0
  62821. };
  62822. }
  62823. if (!currentState) {
  62824. this._buttons[buttonIndex] = {
  62825. pressed: newState.pressed,
  62826. touched: newState.touched,
  62827. value: newState.value
  62828. };
  62829. return;
  62830. }
  62831. this._checkChanges(newState, currentState);
  62832. if (this._changes.changed) {
  62833. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  62834. this.handleButtonChange(buttonIndex, newState, this._changes);
  62835. }
  62836. this._buttons[buttonIndex].pressed = newState.pressed;
  62837. this._buttons[buttonIndex].touched = newState.touched;
  62838. // oculus triggers are never 0, thou not touched.
  62839. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  62840. };
  62841. WebVRController.prototype._checkChanges = function (newState, currentState) {
  62842. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  62843. this._changes.touchChanged = newState.touched !== currentState.touched;
  62844. this._changes.valueChanged = newState.value !== currentState.value;
  62845. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  62846. return this._changes;
  62847. };
  62848. WebVRController.prototype.dispose = function () {
  62849. _super.prototype.dispose.call(this);
  62850. this.onTriggerStateChangedObservable.clear();
  62851. this.onMainButtonStateChangedObservable.clear();
  62852. this.onSecondaryButtonStateChangedObservable.clear();
  62853. this.onPadStateChangedObservable.clear();
  62854. this.onPadValuesChangedObservable.clear();
  62855. };
  62856. return WebVRController;
  62857. }(BABYLON.PoseEnabledController));
  62858. BABYLON.WebVRController = WebVRController;
  62859. })(BABYLON || (BABYLON = {}));
  62860. //# sourceMappingURL=babylon.webVRController.js.map
  62861. var BABYLON;
  62862. (function (BABYLON) {
  62863. var OculusTouchController = /** @class */ (function (_super) {
  62864. __extends(OculusTouchController, _super);
  62865. function OculusTouchController(vrGamepad) {
  62866. var _this = _super.call(this, vrGamepad) || this;
  62867. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  62868. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  62869. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  62870. return _this;
  62871. }
  62872. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  62873. var _this = this;
  62874. var meshName;
  62875. // Hand
  62876. if (this.hand === 'left') {
  62877. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  62878. }
  62879. else {
  62880. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  62881. }
  62882. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  62883. /*
  62884. Parent Mesh name: oculus_touch_left
  62885. - body
  62886. - trigger
  62887. - thumbstick
  62888. - grip
  62889. - button_y
  62890. - button_x
  62891. - button_enter
  62892. */
  62893. _this._defaultModel = newMeshes[1];
  62894. _this.attachToMesh(_this._defaultModel);
  62895. if (meshLoaded) {
  62896. meshLoaded(_this._defaultModel);
  62897. }
  62898. });
  62899. };
  62900. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  62901. // helper getters for left and right hand.
  62902. get: function () {
  62903. if (this.hand === 'right') {
  62904. return this.onMainButtonStateChangedObservable;
  62905. }
  62906. else {
  62907. throw new Error('No A button on left hand');
  62908. }
  62909. },
  62910. enumerable: true,
  62911. configurable: true
  62912. });
  62913. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  62914. get: function () {
  62915. if (this.hand === 'right') {
  62916. return this.onSecondaryButtonStateChangedObservable;
  62917. }
  62918. else {
  62919. throw new Error('No B button on left hand');
  62920. }
  62921. },
  62922. enumerable: true,
  62923. configurable: true
  62924. });
  62925. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  62926. get: function () {
  62927. if (this.hand === 'left') {
  62928. return this.onMainButtonStateChangedObservable;
  62929. }
  62930. else {
  62931. throw new Error('No X button on right hand');
  62932. }
  62933. },
  62934. enumerable: true,
  62935. configurable: true
  62936. });
  62937. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  62938. get: function () {
  62939. if (this.hand === 'left') {
  62940. return this.onSecondaryButtonStateChangedObservable;
  62941. }
  62942. else {
  62943. throw new Error('No Y button on right hand');
  62944. }
  62945. },
  62946. enumerable: true,
  62947. configurable: true
  62948. });
  62949. /*
  62950. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  62951. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  62952. 2) secondary trigger (same)
  62953. 3) A (right) X (left), touch, pressed = value
  62954. 4) B / Y
  62955. 5) thumb rest
  62956. */
  62957. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  62958. var notifyObject = state; //{ state: state, changes: changes };
  62959. var triggerDirection = this.hand === 'right' ? -1 : 1;
  62960. switch (buttonIdx) {
  62961. case 0:
  62962. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  62963. return;
  62964. case 1:// index trigger
  62965. if (this._defaultModel) {
  62966. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  62967. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  62968. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  62969. }
  62970. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  62971. return;
  62972. case 2:// secondary trigger
  62973. if (this._defaultModel) {
  62974. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  62975. }
  62976. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  62977. return;
  62978. case 3:
  62979. if (this._defaultModel) {
  62980. if (notifyObject.pressed) {
  62981. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  62982. }
  62983. else {
  62984. (this._defaultModel.getChildren()[1]).position.y = 0;
  62985. }
  62986. }
  62987. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  62988. return;
  62989. case 4:
  62990. if (this._defaultModel) {
  62991. if (notifyObject.pressed) {
  62992. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  62993. }
  62994. else {
  62995. (this._defaultModel.getChildren()[2]).position.y = 0;
  62996. }
  62997. }
  62998. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  62999. return;
  63000. case 5:
  63001. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  63002. return;
  63003. }
  63004. };
  63005. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  63006. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  63007. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  63008. return OculusTouchController;
  63009. }(BABYLON.WebVRController));
  63010. BABYLON.OculusTouchController = OculusTouchController;
  63011. })(BABYLON || (BABYLON = {}));
  63012. //# sourceMappingURL=babylon.oculusTouchController.js.map
  63013. var BABYLON;
  63014. (function (BABYLON) {
  63015. var ViveController = /** @class */ (function (_super) {
  63016. __extends(ViveController, _super);
  63017. function ViveController(vrGamepad) {
  63018. var _this = _super.call(this, vrGamepad) || this;
  63019. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  63020. _this._invertLeftStickY = true;
  63021. return _this;
  63022. }
  63023. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63024. var _this = this;
  63025. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  63026. /*
  63027. Parent Mesh name: ViveWand
  63028. - body
  63029. - r_gripper
  63030. - l_gripper
  63031. - menu_button
  63032. - system_button
  63033. - trackpad
  63034. - trigger
  63035. - LED
  63036. */
  63037. _this._defaultModel = newMeshes[1];
  63038. _this.attachToMesh(_this._defaultModel);
  63039. if (meshLoaded) {
  63040. meshLoaded(_this._defaultModel);
  63041. }
  63042. });
  63043. };
  63044. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  63045. get: function () {
  63046. return this.onMainButtonStateChangedObservable;
  63047. },
  63048. enumerable: true,
  63049. configurable: true
  63050. });
  63051. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  63052. get: function () {
  63053. return this.onMainButtonStateChangedObservable;
  63054. },
  63055. enumerable: true,
  63056. configurable: true
  63057. });
  63058. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  63059. get: function () {
  63060. return this.onSecondaryButtonStateChangedObservable;
  63061. },
  63062. enumerable: true,
  63063. configurable: true
  63064. });
  63065. /**
  63066. * Vive mapping:
  63067. * 0: touchpad
  63068. * 1: trigger
  63069. * 2: left AND right buttons
  63070. * 3: menu button
  63071. */
  63072. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63073. var notifyObject = state; //{ state: state, changes: changes };
  63074. switch (buttonIdx) {
  63075. case 0:
  63076. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  63077. return;
  63078. case 1:// index trigger
  63079. if (this._defaultModel) {
  63080. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  63081. }
  63082. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  63083. return;
  63084. case 2:// left AND right button
  63085. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  63086. return;
  63087. case 3:
  63088. if (this._defaultModel) {
  63089. if (notifyObject.pressed) {
  63090. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  63091. }
  63092. else {
  63093. (this._defaultModel.getChildren()[2]).position.y = 0;
  63094. }
  63095. }
  63096. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  63097. return;
  63098. }
  63099. };
  63100. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  63101. ViveController.MODEL_FILENAME = 'wand.babylon';
  63102. return ViveController;
  63103. }(BABYLON.WebVRController));
  63104. BABYLON.ViveController = ViveController;
  63105. })(BABYLON || (BABYLON = {}));
  63106. //# sourceMappingURL=babylon.viveController.js.map
  63107. var BABYLON;
  63108. (function (BABYLON) {
  63109. var GenericController = /** @class */ (function (_super) {
  63110. __extends(GenericController, _super);
  63111. function GenericController(vrGamepad) {
  63112. return _super.call(this, vrGamepad) || this;
  63113. }
  63114. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63115. var _this = this;
  63116. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  63117. _this._defaultModel = newMeshes[1];
  63118. _this.attachToMesh(_this._defaultModel);
  63119. if (meshLoaded) {
  63120. meshLoaded(_this._defaultModel);
  63121. }
  63122. });
  63123. };
  63124. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63125. console.log("Button id: " + buttonIdx + "state: ");
  63126. console.dir(state);
  63127. };
  63128. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  63129. GenericController.MODEL_FILENAME = 'generic.babylon';
  63130. return GenericController;
  63131. }(BABYLON.WebVRController));
  63132. BABYLON.GenericController = GenericController;
  63133. })(BABYLON || (BABYLON = {}));
  63134. //# sourceMappingURL=babylon.genericController.js.map
  63135. var BABYLON;
  63136. (function (BABYLON) {
  63137. var LoadedMeshInfo = /** @class */ (function () {
  63138. function LoadedMeshInfo() {
  63139. this.buttonMeshes = {};
  63140. this.axisMeshes = {};
  63141. }
  63142. return LoadedMeshInfo;
  63143. }());
  63144. var WindowsMotionController = /** @class */ (function (_super) {
  63145. __extends(WindowsMotionController, _super);
  63146. function WindowsMotionController(vrGamepad) {
  63147. var _this = _super.call(this, vrGamepad) || this;
  63148. _this._mapping = {
  63149. // Semantic button names
  63150. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  63151. // A mapping of the button name to glTF model node name
  63152. // that should be transformed by button value.
  63153. buttonMeshNames: {
  63154. 'trigger': 'SELECT',
  63155. 'menu': 'MENU',
  63156. 'grip': 'GRASP',
  63157. 'thumbstick': 'THUMBSTICK_PRESS',
  63158. 'trackpad': 'TOUCHPAD_PRESS'
  63159. },
  63160. // This mapping is used to translate from the Motion Controller to Babylon semantics
  63161. buttonObservableNames: {
  63162. 'trigger': 'onTriggerStateChangedObservable',
  63163. 'menu': 'onSecondaryButtonStateChangedObservable',
  63164. 'grip': 'onMainButtonStateChangedObservable',
  63165. 'thumbstick': 'onPadStateChangedObservable',
  63166. 'trackpad': 'onTrackpadChangedObservable'
  63167. },
  63168. // A mapping of the axis name to glTF model node name
  63169. // that should be transformed by axis value.
  63170. // This array mirrors the browserGamepad.axes array, such that
  63171. // the mesh corresponding to axis 0 is in this array index 0.
  63172. axisMeshNames: [
  63173. 'THUMBSTICK_X',
  63174. 'THUMBSTICK_Y',
  63175. 'TOUCHPAD_TOUCH_X',
  63176. 'TOUCHPAD_TOUCH_Y'
  63177. ],
  63178. pointingPoseMeshName: 'POINTING_POSE'
  63179. };
  63180. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  63181. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  63182. _this.trackpad = { x: 0, y: 0 };
  63183. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  63184. _this._loadedMeshInfo = null;
  63185. return _this;
  63186. }
  63187. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  63188. get: function () {
  63189. return this.onTriggerStateChangedObservable;
  63190. },
  63191. enumerable: true,
  63192. configurable: true
  63193. });
  63194. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  63195. get: function () {
  63196. return this.onSecondaryButtonStateChangedObservable;
  63197. },
  63198. enumerable: true,
  63199. configurable: true
  63200. });
  63201. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  63202. get: function () {
  63203. return this.onMainButtonStateChangedObservable;
  63204. },
  63205. enumerable: true,
  63206. configurable: true
  63207. });
  63208. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  63209. get: function () {
  63210. return this.onPadStateChangedObservable;
  63211. },
  63212. enumerable: true,
  63213. configurable: true
  63214. });
  63215. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  63216. get: function () {
  63217. return this.onTrackpadChangedObservable;
  63218. },
  63219. enumerable: true,
  63220. configurable: true
  63221. });
  63222. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  63223. get: function () {
  63224. return this.onTrackpadValuesChangedObservable;
  63225. },
  63226. enumerable: true,
  63227. configurable: true
  63228. });
  63229. /**
  63230. * Called once per frame by the engine.
  63231. */
  63232. WindowsMotionController.prototype.update = function () {
  63233. _super.prototype.update.call(this);
  63234. // Only need to animate axes if there is a loaded mesh
  63235. if (this._loadedMeshInfo) {
  63236. if (this.browserGamepad.axes) {
  63237. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  63238. this.trackpad.x = this.browserGamepad["axes"][2];
  63239. this.trackpad.y = this.browserGamepad["axes"][3];
  63240. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  63241. }
  63242. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  63243. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  63244. }
  63245. }
  63246. }
  63247. };
  63248. /**
  63249. * Called once for each button that changed state since the last frame
  63250. * @param buttonIdx Which button index changed
  63251. * @param state New state of the button
  63252. * @param changes Which properties on the state changed since last frame
  63253. */
  63254. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63255. var buttonName = this._mapping.buttons[buttonIdx];
  63256. if (!buttonName) {
  63257. return;
  63258. }
  63259. // Only emit events for buttons that we know how to map from index to name
  63260. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  63261. if (observable) {
  63262. observable.notifyObservers(state);
  63263. }
  63264. this.lerpButtonTransform(buttonName, state.value);
  63265. };
  63266. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  63267. // If there is no loaded mesh, there is nothing to transform.
  63268. if (!this._loadedMeshInfo) {
  63269. return;
  63270. }
  63271. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  63272. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  63273. return;
  63274. }
  63275. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  63276. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  63277. };
  63278. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  63279. if (!this._loadedMeshInfo) {
  63280. return;
  63281. }
  63282. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  63283. if (!meshInfo) {
  63284. return;
  63285. }
  63286. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  63287. return;
  63288. }
  63289. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  63290. var lerpValue = axisValue * 0.5 + 0.5;
  63291. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  63292. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  63293. };
  63294. /**
  63295. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  63296. * @param scene scene in which to add meshes
  63297. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  63298. */
  63299. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  63300. var _this = this;
  63301. if (forceDefault === void 0) { forceDefault = false; }
  63302. var path;
  63303. var filename;
  63304. // Checking if GLB loader is present
  63305. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  63306. // Determine the device specific folder based on the ID suffix
  63307. var device = 'default';
  63308. if (this.id && !forceDefault) {
  63309. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  63310. device = ((match && match[0]) || device);
  63311. }
  63312. // Hand
  63313. if (this.hand === 'left') {
  63314. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  63315. }
  63316. else {
  63317. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  63318. }
  63319. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  63320. }
  63321. else {
  63322. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  63323. path = BABYLON.GenericController.MODEL_BASE_URL;
  63324. filename = BABYLON.GenericController.MODEL_FILENAME;
  63325. }
  63326. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  63327. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  63328. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  63329. if (!_this._loadedMeshInfo) {
  63330. return;
  63331. }
  63332. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  63333. _this.attachToMesh(_this._defaultModel);
  63334. if (meshLoaded) {
  63335. meshLoaded(_this._defaultModel);
  63336. }
  63337. }, null, function (scene, message) {
  63338. BABYLON.Tools.Log(message);
  63339. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  63340. if (!forceDefault) {
  63341. _this.initControllerMesh(scene, meshLoaded, true);
  63342. }
  63343. });
  63344. };
  63345. /**
  63346. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  63347. * can be transformed by button presses and axes values, based on this._mapping.
  63348. *
  63349. * @param scene scene in which the meshes exist
  63350. * @param meshes list of meshes that make up the controller model to process
  63351. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  63352. */
  63353. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  63354. var loadedMeshInfo = null;
  63355. // Create a new mesh to contain the glTF hierarchy
  63356. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  63357. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  63358. var childMesh = null;
  63359. for (var i = 0; i < meshes.length; i++) {
  63360. var mesh = meshes[i];
  63361. if (!mesh.parent) {
  63362. // Exclude controller meshes from picking results
  63363. mesh.isPickable = false;
  63364. // Handle root node, attach to the new parentMesh
  63365. childMesh = mesh;
  63366. break;
  63367. }
  63368. }
  63369. if (childMesh) {
  63370. childMesh.setParent(parentMesh);
  63371. // Create our mesh info. Note that this method will always return non-null.
  63372. loadedMeshInfo = this.createMeshInfo(parentMesh);
  63373. }
  63374. else {
  63375. BABYLON.Tools.Warn('Could not find root node in model file.');
  63376. }
  63377. return loadedMeshInfo;
  63378. };
  63379. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  63380. var loadedMeshInfo = new LoadedMeshInfo();
  63381. var i;
  63382. loadedMeshInfo.rootNode = rootNode;
  63383. // Reset the caches
  63384. loadedMeshInfo.buttonMeshes = {};
  63385. loadedMeshInfo.axisMeshes = {};
  63386. // Button Meshes
  63387. for (i = 0; i < this._mapping.buttons.length; i++) {
  63388. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  63389. if (!buttonMeshName) {
  63390. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  63391. continue;
  63392. }
  63393. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  63394. if (!buttonMesh) {
  63395. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  63396. continue;
  63397. }
  63398. var buttonMeshInfo = {
  63399. index: i,
  63400. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  63401. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  63402. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  63403. };
  63404. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  63405. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  63406. }
  63407. else {
  63408. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  63409. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  63410. '(VALUE: ' + !!buttonMeshInfo.value +
  63411. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  63412. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  63413. ')');
  63414. }
  63415. }
  63416. // Axis Meshes
  63417. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  63418. var axisMeshName = this._mapping.axisMeshNames[i];
  63419. if (!axisMeshName) {
  63420. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  63421. continue;
  63422. }
  63423. var axisMesh = getChildByName(rootNode, axisMeshName);
  63424. if (!axisMesh) {
  63425. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  63426. continue;
  63427. }
  63428. var axisMeshInfo = {
  63429. index: i,
  63430. value: getImmediateChildByName(axisMesh, 'VALUE'),
  63431. min: getImmediateChildByName(axisMesh, 'MIN'),
  63432. max: getImmediateChildByName(axisMesh, 'MAX')
  63433. };
  63434. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  63435. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  63436. }
  63437. else {
  63438. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  63439. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  63440. '(VALUE: ' + !!axisMeshInfo.value +
  63441. ', MIN: ' + !!axisMeshInfo.min +
  63442. ', MAX:' + !!axisMeshInfo.max +
  63443. ')');
  63444. }
  63445. }
  63446. // Pointing Ray
  63447. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  63448. if (!loadedMeshInfo.pointingPoseNode) {
  63449. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  63450. }
  63451. return loadedMeshInfo;
  63452. // Look through all children recursively. This will return null if no mesh exists with the given name.
  63453. function getChildByName(node, name) {
  63454. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  63455. }
  63456. // Look through only immediate children. This will return null if no mesh exists with the given name.
  63457. function getImmediateChildByName(node, name) {
  63458. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  63459. }
  63460. };
  63461. WindowsMotionController.prototype.getForwardRay = function (length) {
  63462. if (length === void 0) { length = 100; }
  63463. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  63464. return _super.prototype.getForwardRay.call(this, length);
  63465. }
  63466. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  63467. var origin = m.getTranslation();
  63468. var forward = new BABYLON.Vector3(0, 0, -1);
  63469. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  63470. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  63471. return new BABYLON.Ray(origin, direction, length);
  63472. };
  63473. WindowsMotionController.prototype.dispose = function () {
  63474. _super.prototype.dispose.call(this);
  63475. this.onTrackpadChangedObservable.clear();
  63476. };
  63477. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  63478. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  63479. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  63480. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  63481. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  63482. return WindowsMotionController;
  63483. }(BABYLON.WebVRController));
  63484. BABYLON.WindowsMotionController = WindowsMotionController;
  63485. })(BABYLON || (BABYLON = {}));
  63486. //# sourceMappingURL=babylon.windowsMotionController.js.map
  63487. var BABYLON;
  63488. (function (BABYLON) {
  63489. var GearVRController = /** @class */ (function (_super) {
  63490. __extends(GearVRController, _super);
  63491. function GearVRController(vrGamepad) {
  63492. var _this = _super.call(this, vrGamepad) || this;
  63493. _this._buttonIndexToObservableNameMap = [
  63494. 'onTrackpadChangedObservable',
  63495. 'onTriggerStateChangedObservable' // Trigger
  63496. ];
  63497. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  63498. return _this;
  63499. }
  63500. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63501. var _this = this;
  63502. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  63503. _this._defaultModel = newMeshes[1];
  63504. _this.attachToMesh(_this._defaultModel);
  63505. if (meshLoaded) {
  63506. meshLoaded(_this._defaultModel);
  63507. }
  63508. });
  63509. };
  63510. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63511. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  63512. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  63513. // Only emit events for buttons that we know how to map from index to observable
  63514. var observable = this[observableName];
  63515. if (observable) {
  63516. observable.notifyObservers(state);
  63517. }
  63518. }
  63519. };
  63520. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  63521. GearVRController.MODEL_FILENAME = 'generic.babylon';
  63522. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  63523. return GearVRController;
  63524. }(BABYLON.WebVRController));
  63525. BABYLON.GearVRController = GearVRController;
  63526. })(BABYLON || (BABYLON = {}));
  63527. //# sourceMappingURL=babylon.gearVRController.js.map
  63528. var BABYLON;
  63529. (function (BABYLON) {
  63530. var FollowCamera = /** @class */ (function (_super) {
  63531. __extends(FollowCamera, _super);
  63532. function FollowCamera(name, position, scene, lockedTarget) {
  63533. if (lockedTarget === void 0) { lockedTarget = null; }
  63534. var _this = _super.call(this, name, position, scene) || this;
  63535. _this.radius = 12;
  63536. _this.rotationOffset = 0;
  63537. _this.heightOffset = 4;
  63538. _this.cameraAcceleration = 0.05;
  63539. _this.maxCameraSpeed = 20;
  63540. _this.lockedTarget = lockedTarget;
  63541. return _this;
  63542. }
  63543. FollowCamera.prototype.getRadians = function (degrees) {
  63544. return degrees * Math.PI / 180;
  63545. };
  63546. FollowCamera.prototype.follow = function (cameraTarget) {
  63547. if (!cameraTarget)
  63548. return;
  63549. var yRotation;
  63550. if (cameraTarget.rotationQuaternion) {
  63551. var rotMatrix = new BABYLON.Matrix();
  63552. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  63553. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  63554. }
  63555. else {
  63556. yRotation = cameraTarget.rotation.y;
  63557. }
  63558. var radians = this.getRadians(this.rotationOffset) + yRotation;
  63559. var targetPosition = cameraTarget.getAbsolutePosition();
  63560. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  63561. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  63562. var dx = targetX - this.position.x;
  63563. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  63564. var dz = (targetZ) - this.position.z;
  63565. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  63566. var vy = dy * this.cameraAcceleration;
  63567. var vz = dz * this.cameraAcceleration * 2;
  63568. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  63569. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  63570. }
  63571. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  63572. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  63573. }
  63574. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  63575. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  63576. }
  63577. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  63578. this.setTarget(targetPosition);
  63579. };
  63580. FollowCamera.prototype._checkInputs = function () {
  63581. _super.prototype._checkInputs.call(this);
  63582. if (this.lockedTarget) {
  63583. this.follow(this.lockedTarget);
  63584. }
  63585. };
  63586. FollowCamera.prototype.getClassName = function () {
  63587. return "FollowCamera";
  63588. };
  63589. __decorate([
  63590. BABYLON.serialize()
  63591. ], FollowCamera.prototype, "radius", void 0);
  63592. __decorate([
  63593. BABYLON.serialize()
  63594. ], FollowCamera.prototype, "rotationOffset", void 0);
  63595. __decorate([
  63596. BABYLON.serialize()
  63597. ], FollowCamera.prototype, "heightOffset", void 0);
  63598. __decorate([
  63599. BABYLON.serialize()
  63600. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  63601. __decorate([
  63602. BABYLON.serialize()
  63603. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  63604. __decorate([
  63605. BABYLON.serializeAsMeshReference("lockedTargetId")
  63606. ], FollowCamera.prototype, "lockedTarget", void 0);
  63607. return FollowCamera;
  63608. }(BABYLON.TargetCamera));
  63609. BABYLON.FollowCamera = FollowCamera;
  63610. var ArcFollowCamera = /** @class */ (function (_super) {
  63611. __extends(ArcFollowCamera, _super);
  63612. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  63613. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  63614. _this.alpha = alpha;
  63615. _this.beta = beta;
  63616. _this.radius = radius;
  63617. _this.target = target;
  63618. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  63619. _this.follow();
  63620. return _this;
  63621. }
  63622. ArcFollowCamera.prototype.follow = function () {
  63623. if (!this.target) {
  63624. return;
  63625. }
  63626. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  63627. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  63628. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  63629. var targetPosition = this.target.getAbsolutePosition();
  63630. this.position = targetPosition.add(this._cartesianCoordinates);
  63631. this.setTarget(targetPosition);
  63632. };
  63633. ArcFollowCamera.prototype._checkInputs = function () {
  63634. _super.prototype._checkInputs.call(this);
  63635. this.follow();
  63636. };
  63637. ArcFollowCamera.prototype.getClassName = function () {
  63638. return "ArcFollowCamera";
  63639. };
  63640. return ArcFollowCamera;
  63641. }(BABYLON.TargetCamera));
  63642. BABYLON.ArcFollowCamera = ArcFollowCamera;
  63643. })(BABYLON || (BABYLON = {}));
  63644. //# sourceMappingURL=babylon.followCamera.js.map
  63645. var BABYLON;
  63646. (function (BABYLON) {
  63647. // We're mainly based on the logic defined into the FreeCamera code
  63648. var UniversalCamera = /** @class */ (function (_super) {
  63649. __extends(UniversalCamera, _super);
  63650. //-- end properties for backward compatibility for inputs
  63651. function UniversalCamera(name, position, scene) {
  63652. var _this = _super.call(this, name, position, scene) || this;
  63653. _this.inputs.addGamepad();
  63654. return _this;
  63655. }
  63656. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  63657. //-- Begin properties for backward compatibility for inputs
  63658. get: function () {
  63659. var gamepad = this.inputs.attached["gamepad"];
  63660. if (gamepad)
  63661. return gamepad.gamepadAngularSensibility;
  63662. return 0;
  63663. },
  63664. set: function (value) {
  63665. var gamepad = this.inputs.attached["gamepad"];
  63666. if (gamepad)
  63667. gamepad.gamepadAngularSensibility = value;
  63668. },
  63669. enumerable: true,
  63670. configurable: true
  63671. });
  63672. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  63673. get: function () {
  63674. var gamepad = this.inputs.attached["gamepad"];
  63675. if (gamepad)
  63676. return gamepad.gamepadMoveSensibility;
  63677. return 0;
  63678. },
  63679. set: function (value) {
  63680. var gamepad = this.inputs.attached["gamepad"];
  63681. if (gamepad)
  63682. gamepad.gamepadMoveSensibility = value;
  63683. },
  63684. enumerable: true,
  63685. configurable: true
  63686. });
  63687. UniversalCamera.prototype.getClassName = function () {
  63688. return "UniversalCamera";
  63689. };
  63690. return UniversalCamera;
  63691. }(BABYLON.TouchCamera));
  63692. BABYLON.UniversalCamera = UniversalCamera;
  63693. })(BABYLON || (BABYLON = {}));
  63694. //# sourceMappingURL=babylon.universalCamera.js.map
  63695. var BABYLON;
  63696. (function (BABYLON) {
  63697. // We're mainly based on the logic defined into the FreeCamera code
  63698. var GamepadCamera = /** @class */ (function (_super) {
  63699. __extends(GamepadCamera, _super);
  63700. //-- end properties for backward compatibility for inputs
  63701. function GamepadCamera(name, position, scene) {
  63702. return _super.call(this, name, position, scene) || this;
  63703. }
  63704. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  63705. //-- Begin properties for backward compatibility for inputs
  63706. get: function () {
  63707. var gamepad = this.inputs.attached["gamepad"];
  63708. if (gamepad)
  63709. return gamepad.gamepadAngularSensibility;
  63710. return 0;
  63711. },
  63712. set: function (value) {
  63713. var gamepad = this.inputs.attached["gamepad"];
  63714. if (gamepad)
  63715. gamepad.gamepadAngularSensibility = value;
  63716. },
  63717. enumerable: true,
  63718. configurable: true
  63719. });
  63720. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  63721. get: function () {
  63722. var gamepad = this.inputs.attached["gamepad"];
  63723. if (gamepad)
  63724. return gamepad.gamepadMoveSensibility;
  63725. return 0;
  63726. },
  63727. set: function (value) {
  63728. var gamepad = this.inputs.attached["gamepad"];
  63729. if (gamepad)
  63730. gamepad.gamepadMoveSensibility = value;
  63731. },
  63732. enumerable: true,
  63733. configurable: true
  63734. });
  63735. GamepadCamera.prototype.getClassName = function () {
  63736. return "GamepadCamera";
  63737. };
  63738. return GamepadCamera;
  63739. }(BABYLON.UniversalCamera));
  63740. BABYLON.GamepadCamera = GamepadCamera;
  63741. })(BABYLON || (BABYLON = {}));
  63742. //# sourceMappingURL=babylon.gamepadCamera.js.map
  63743. var BABYLON;
  63744. (function (BABYLON) {
  63745. var PostProcessRenderPipelineManager = /** @class */ (function () {
  63746. function PostProcessRenderPipelineManager() {
  63747. this._renderPipelines = {};
  63748. }
  63749. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  63750. this._renderPipelines[renderPipeline._name] = renderPipeline;
  63751. };
  63752. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  63753. if (unique === void 0) { unique = false; }
  63754. var renderPipeline = this._renderPipelines[renderPipelineName];
  63755. if (!renderPipeline) {
  63756. return;
  63757. }
  63758. renderPipeline._attachCameras(cameras, unique);
  63759. };
  63760. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  63761. var renderPipeline = this._renderPipelines[renderPipelineName];
  63762. if (!renderPipeline) {
  63763. return;
  63764. }
  63765. renderPipeline._detachCameras(cameras);
  63766. };
  63767. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  63768. var renderPipeline = this._renderPipelines[renderPipelineName];
  63769. if (!renderPipeline) {
  63770. return;
  63771. }
  63772. renderPipeline._enableEffect(renderEffectName, cameras);
  63773. };
  63774. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  63775. var renderPipeline = this._renderPipelines[renderPipelineName];
  63776. if (!renderPipeline) {
  63777. return;
  63778. }
  63779. renderPipeline._disableEffect(renderEffectName, cameras);
  63780. };
  63781. PostProcessRenderPipelineManager.prototype.update = function () {
  63782. for (var renderPipelineName in this._renderPipelines) {
  63783. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  63784. var pipeline = this._renderPipelines[renderPipelineName];
  63785. if (!pipeline.isSupported) {
  63786. pipeline.dispose();
  63787. delete this._renderPipelines[renderPipelineName];
  63788. }
  63789. else {
  63790. pipeline._update();
  63791. }
  63792. }
  63793. }
  63794. };
  63795. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  63796. for (var renderPipelineName in this._renderPipelines) {
  63797. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  63798. var pipeline = this._renderPipelines[renderPipelineName];
  63799. pipeline._rebuild();
  63800. }
  63801. }
  63802. };
  63803. PostProcessRenderPipelineManager.prototype.dispose = function () {
  63804. for (var renderPipelineName in this._renderPipelines) {
  63805. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  63806. var pipeline = this._renderPipelines[renderPipelineName];
  63807. pipeline.dispose();
  63808. }
  63809. }
  63810. };
  63811. return PostProcessRenderPipelineManager;
  63812. }());
  63813. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  63814. })(BABYLON || (BABYLON = {}));
  63815. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  63816. var BABYLON;
  63817. (function (BABYLON) {
  63818. /**
  63819. * This represents a set of one or more post processes in Babylon.
  63820. * A post process can be used to apply a shader to a texture after it is rendered.
  63821. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  63822. */
  63823. var PostProcessRenderEffect = /** @class */ (function () {
  63824. /**
  63825. * Instantiates a post process render effect.
  63826. * A post process can be used to apply a shader to a texture after it is rendered.
  63827. * @param engine The engine the effect is tied to
  63828. * @param name The name of the effect
  63829. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  63830. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  63831. */
  63832. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  63833. this._name = name;
  63834. this._singleInstance = singleInstance || true;
  63835. this._getPostProcesses = getPostProcesses;
  63836. this._cameras = {};
  63837. this._indicesForCamera = {};
  63838. this._postProcesses = {};
  63839. }
  63840. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  63841. /**
  63842. * Checks if all the post processes in the effect are supported.
  63843. */
  63844. get: function () {
  63845. for (var index in this._postProcesses) {
  63846. for (var ppIndex in this._postProcesses[index]) {
  63847. if (!this._postProcesses[index][ppIndex].isSupported) {
  63848. return false;
  63849. }
  63850. }
  63851. }
  63852. return true;
  63853. },
  63854. enumerable: true,
  63855. configurable: true
  63856. });
  63857. /**
  63858. * Updates the current state of the effect
  63859. */
  63860. PostProcessRenderEffect.prototype._update = function () {
  63861. };
  63862. /**
  63863. * Attaches the effect on cameras
  63864. * @param cameras The camera to attach to.
  63865. */
  63866. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  63867. var _this = this;
  63868. var cameraKey;
  63869. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  63870. if (!cams) {
  63871. return;
  63872. }
  63873. for (var i = 0; i < cams.length; i++) {
  63874. var camera = cams[i];
  63875. var cameraName = camera.name;
  63876. if (this._singleInstance) {
  63877. cameraKey = 0;
  63878. }
  63879. else {
  63880. cameraKey = cameraName;
  63881. }
  63882. if (!this._postProcesses[cameraKey]) {
  63883. var postProcess = this._getPostProcesses();
  63884. if (postProcess) {
  63885. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  63886. }
  63887. }
  63888. if (!this._indicesForCamera[cameraName]) {
  63889. this._indicesForCamera[cameraName] = [];
  63890. }
  63891. this._postProcesses[cameraKey].forEach(function (postProcess) {
  63892. var index = camera.attachPostProcess(postProcess);
  63893. _this._indicesForCamera[cameraName].push(index);
  63894. });
  63895. if (!this._cameras[cameraName]) {
  63896. this._cameras[cameraName] = camera;
  63897. }
  63898. }
  63899. };
  63900. /**
  63901. * Detatches the effect on cameras
  63902. * @param cameras The camera to detatch from.
  63903. */
  63904. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  63905. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  63906. if (!cams) {
  63907. return;
  63908. }
  63909. for (var i = 0; i < cams.length; i++) {
  63910. var camera = cams[i];
  63911. var cameraName = camera.name;
  63912. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  63913. camera.detachPostProcess(postProcess);
  63914. });
  63915. if (this._cameras[cameraName]) {
  63916. //this._indicesForCamera.splice(index, 1);
  63917. this._cameras[cameraName] = null;
  63918. }
  63919. }
  63920. };
  63921. /**
  63922. * Enables the effect on given cameras
  63923. * @param cameras The camera to enable.
  63924. */
  63925. PostProcessRenderEffect.prototype._enable = function (cameras) {
  63926. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  63927. if (!cams) {
  63928. return;
  63929. }
  63930. for (var i = 0; i < cams.length; i++) {
  63931. var camera = cams[i];
  63932. var cameraName = camera.name;
  63933. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  63934. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  63935. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  63936. }
  63937. }
  63938. }
  63939. };
  63940. /**
  63941. * Disables the effect on the given cameras
  63942. * @param cameras The camera to disable.
  63943. */
  63944. PostProcessRenderEffect.prototype._disable = function (cameras) {
  63945. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  63946. if (!cams) {
  63947. return;
  63948. }
  63949. for (var i = 0; i < cams.length; i++) {
  63950. var camera = cams[i];
  63951. var cameraName = camera.Name;
  63952. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  63953. }
  63954. };
  63955. /**
  63956. * Gets a list of the post processes contained in the effect.
  63957. * @param camera The camera to get the post processes on.
  63958. * @returns The list of the post processes in the effect.
  63959. */
  63960. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  63961. if (this._singleInstance) {
  63962. return this._postProcesses[0];
  63963. }
  63964. else {
  63965. if (!camera) {
  63966. return null;
  63967. }
  63968. return this._postProcesses[camera.name];
  63969. }
  63970. };
  63971. return PostProcessRenderEffect;
  63972. }());
  63973. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  63974. })(BABYLON || (BABYLON = {}));
  63975. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  63976. var BABYLON;
  63977. (function (BABYLON) {
  63978. var PostProcessRenderPipeline = /** @class */ (function () {
  63979. function PostProcessRenderPipeline(engine, name) {
  63980. this._name = name;
  63981. this._renderEffects = {};
  63982. this._renderEffectsForIsolatedPass = new Array();
  63983. this._cameras = [];
  63984. }
  63985. PostProcessRenderPipeline.prototype.getClassName = function () {
  63986. return "PostProcessRenderPipeline";
  63987. };
  63988. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  63989. get: function () {
  63990. for (var renderEffectName in this._renderEffects) {
  63991. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  63992. if (!this._renderEffects[renderEffectName].isSupported) {
  63993. return false;
  63994. }
  63995. }
  63996. }
  63997. return true;
  63998. },
  63999. enumerable: true,
  64000. configurable: true
  64001. });
  64002. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  64003. this._renderEffects[renderEffect._name] = renderEffect;
  64004. };
  64005. // private
  64006. PostProcessRenderPipeline.prototype._rebuild = function () {
  64007. };
  64008. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  64009. var renderEffects = this._renderEffects[renderEffectName];
  64010. if (!renderEffects) {
  64011. return;
  64012. }
  64013. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  64014. };
  64015. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  64016. var renderEffects = this._renderEffects[renderEffectName];
  64017. if (!renderEffects) {
  64018. return;
  64019. }
  64020. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  64021. };
  64022. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  64023. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64024. if (!cams) {
  64025. return;
  64026. }
  64027. var indicesToDelete = [];
  64028. var i;
  64029. for (i = 0; i < cams.length; i++) {
  64030. var camera = cams[i];
  64031. var cameraName = camera.name;
  64032. if (this._cameras.indexOf(camera) === -1) {
  64033. this._cameras[cameraName] = camera;
  64034. }
  64035. else if (unique) {
  64036. indicesToDelete.push(i);
  64037. }
  64038. }
  64039. for (i = 0; i < indicesToDelete.length; i++) {
  64040. cameras.splice(indicesToDelete[i], 1);
  64041. }
  64042. for (var renderEffectName in this._renderEffects) {
  64043. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64044. this._renderEffects[renderEffectName]._attachCameras(cams);
  64045. }
  64046. }
  64047. };
  64048. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  64049. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64050. if (!cams) {
  64051. return;
  64052. }
  64053. for (var renderEffectName in this._renderEffects) {
  64054. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64055. this._renderEffects[renderEffectName]._detachCameras(cams);
  64056. }
  64057. }
  64058. for (var i = 0; i < cams.length; i++) {
  64059. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  64060. }
  64061. };
  64062. PostProcessRenderPipeline.prototype._update = function () {
  64063. for (var renderEffectName in this._renderEffects) {
  64064. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64065. this._renderEffects[renderEffectName]._update();
  64066. }
  64067. }
  64068. for (var i = 0; i < this._cameras.length; i++) {
  64069. var cameraName = this._cameras[i].name;
  64070. if (this._renderEffectsForIsolatedPass[cameraName]) {
  64071. this._renderEffectsForIsolatedPass[cameraName]._update();
  64072. }
  64073. }
  64074. };
  64075. PostProcessRenderPipeline.prototype._reset = function () {
  64076. this._renderEffects = {};
  64077. this._renderEffectsForIsolatedPass = new Array();
  64078. };
  64079. PostProcessRenderPipeline.prototype.dispose = function () {
  64080. // Must be implemented by children
  64081. };
  64082. __decorate([
  64083. BABYLON.serialize()
  64084. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  64085. return PostProcessRenderPipeline;
  64086. }());
  64087. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  64088. })(BABYLON || (BABYLON = {}));
  64089. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  64090. var BABYLON;
  64091. (function (BABYLON) {
  64092. var DepthRenderer = /** @class */ (function () {
  64093. function DepthRenderer(scene, type) {
  64094. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  64095. var _this = this;
  64096. this._scene = scene;
  64097. var engine = scene.getEngine();
  64098. // Render target
  64099. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  64100. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64101. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64102. this._depthMap.refreshRate = 1;
  64103. this._depthMap.renderParticles = false;
  64104. this._depthMap.renderList = null;
  64105. // set default depth value to 1.0 (far away)
  64106. this._depthMap.onClearObservable.add(function (engine) {
  64107. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  64108. });
  64109. // Custom render function
  64110. var renderSubMesh = function (subMesh) {
  64111. var mesh = subMesh.getRenderingMesh();
  64112. var scene = _this._scene;
  64113. var engine = scene.getEngine();
  64114. var material = subMesh.getMaterial();
  64115. if (!material) {
  64116. return;
  64117. }
  64118. // Culling and reverse (right handed system)
  64119. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  64120. // Managing instances
  64121. var batch = mesh._getInstancesRenderList(subMesh._id);
  64122. if (batch.mustReturn) {
  64123. return;
  64124. }
  64125. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  64126. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  64127. engine.enableEffect(_this._effect);
  64128. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  64129. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  64130. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  64131. // Alpha test
  64132. if (material && material.needAlphaTesting()) {
  64133. var alphaTexture = material.getAlphaTestTexture();
  64134. if (alphaTexture) {
  64135. _this._effect.setTexture("diffuseSampler", alphaTexture);
  64136. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  64137. }
  64138. }
  64139. // Bones
  64140. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  64141. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  64142. }
  64143. // Draw
  64144. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  64145. }
  64146. };
  64147. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64148. var index;
  64149. if (depthOnlySubMeshes.length) {
  64150. engine.setColorWrite(false);
  64151. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64152. renderSubMesh(depthOnlySubMeshes.data[index]);
  64153. }
  64154. engine.setColorWrite(true);
  64155. }
  64156. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64157. renderSubMesh(opaqueSubMeshes.data[index]);
  64158. }
  64159. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64160. renderSubMesh(alphaTestSubMeshes.data[index]);
  64161. }
  64162. };
  64163. }
  64164. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  64165. var material = subMesh.getMaterial();
  64166. if (material.disableDepthWrite) {
  64167. return false;
  64168. }
  64169. var defines = [];
  64170. var attribs = [BABYLON.VertexBuffer.PositionKind];
  64171. var mesh = subMesh.getMesh();
  64172. // Alpha test
  64173. if (material && material.needAlphaTesting()) {
  64174. defines.push("#define ALPHATEST");
  64175. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64176. attribs.push(BABYLON.VertexBuffer.UVKind);
  64177. defines.push("#define UV1");
  64178. }
  64179. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  64180. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  64181. defines.push("#define UV2");
  64182. }
  64183. }
  64184. // Bones
  64185. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64186. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64187. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64188. if (mesh.numBoneInfluencers > 4) {
  64189. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  64190. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  64191. }
  64192. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64193. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  64194. }
  64195. else {
  64196. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64197. }
  64198. // Instances
  64199. if (useInstances) {
  64200. defines.push("#define INSTANCES");
  64201. attribs.push("world0");
  64202. attribs.push("world1");
  64203. attribs.push("world2");
  64204. attribs.push("world3");
  64205. }
  64206. // Get correct effect
  64207. var join = defines.join("\n");
  64208. if (this._cachedDefines !== join) {
  64209. this._cachedDefines = join;
  64210. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  64211. }
  64212. return this._effect.isReady();
  64213. };
  64214. DepthRenderer.prototype.getDepthMap = function () {
  64215. return this._depthMap;
  64216. };
  64217. // Methods
  64218. DepthRenderer.prototype.dispose = function () {
  64219. this._depthMap.dispose();
  64220. };
  64221. return DepthRenderer;
  64222. }());
  64223. BABYLON.DepthRenderer = DepthRenderer;
  64224. })(BABYLON || (BABYLON = {}));
  64225. //# sourceMappingURL=babylon.depthRenderer.js.map
  64226. var BABYLON;
  64227. (function (BABYLON) {
  64228. var SSAORenderingPipeline = /** @class */ (function (_super) {
  64229. __extends(SSAORenderingPipeline, _super);
  64230. /**
  64231. * @constructor
  64232. * @param {string} name - The rendering pipeline name
  64233. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  64234. * @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 }
  64235. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  64236. */
  64237. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  64238. var _this = _super.call(this, scene.getEngine(), name) || this;
  64239. // Members
  64240. /**
  64241. * The PassPostProcess id in the pipeline that contains the original scene color
  64242. * @type {string}
  64243. */
  64244. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  64245. /**
  64246. * The SSAO PostProcess id in the pipeline
  64247. * @type {string}
  64248. */
  64249. _this.SSAORenderEffect = "SSAORenderEffect";
  64250. /**
  64251. * The horizontal blur PostProcess id in the pipeline
  64252. * @type {string}
  64253. */
  64254. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  64255. /**
  64256. * The vertical blur PostProcess id in the pipeline
  64257. * @type {string}
  64258. */
  64259. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  64260. /**
  64261. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  64262. * @type {string}
  64263. */
  64264. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  64265. /**
  64266. * The output strength of the SSAO post-process. Default value is 1.0.
  64267. * @type {number}
  64268. */
  64269. _this.totalStrength = 1.0;
  64270. /**
  64271. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  64272. * @type {number}
  64273. */
  64274. _this.radius = 0.0001;
  64275. /**
  64276. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  64277. * Must not be equal to fallOff and superior to fallOff.
  64278. * Default value is 0.975
  64279. * @type {number}
  64280. */
  64281. _this.area = 0.0075;
  64282. /**
  64283. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  64284. * Must not be equal to area and inferior to area.
  64285. * Default value is 0.0
  64286. * @type {number}
  64287. */
  64288. _this.fallOff = 0.000001;
  64289. /**
  64290. * The base color of the SSAO post-process
  64291. * The final result is "base + ssao" between [0, 1]
  64292. * @type {number}
  64293. */
  64294. _this.base = 0.5;
  64295. _this._firstUpdate = true;
  64296. _this._scene = scene;
  64297. // Set up assets
  64298. _this._createRandomTexture();
  64299. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  64300. var ssaoRatio = ratio.ssaoRatio || ratio;
  64301. var combineRatio = ratio.combineRatio || ratio;
  64302. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  64303. _this._createSSAOPostProcess(ssaoRatio);
  64304. _this._createBlurPostProcess(ssaoRatio);
  64305. _this._createSSAOCombinePostProcess(combineRatio);
  64306. // Set up pipeline
  64307. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  64308. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  64309. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  64310. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  64311. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  64312. // Finish
  64313. scene.postProcessRenderPipelineManager.addPipeline(_this);
  64314. if (cameras)
  64315. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  64316. return _this;
  64317. }
  64318. // Public Methods
  64319. /**
  64320. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  64321. */
  64322. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  64323. if (disableDepthRender === void 0) { disableDepthRender = false; }
  64324. for (var i = 0; i < this._scene.cameras.length; i++) {
  64325. var camera = this._scene.cameras[i];
  64326. this._originalColorPostProcess.dispose(camera);
  64327. this._ssaoPostProcess.dispose(camera);
  64328. this._blurHPostProcess.dispose(camera);
  64329. this._blurVPostProcess.dispose(camera);
  64330. this._ssaoCombinePostProcess.dispose(camera);
  64331. }
  64332. this._randomTexture.dispose();
  64333. if (disableDepthRender)
  64334. this._scene.disableDepthRenderer();
  64335. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  64336. _super.prototype.dispose.call(this);
  64337. };
  64338. // Private Methods
  64339. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  64340. var _this = this;
  64341. var size = 16;
  64342. 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);
  64343. 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);
  64344. this._blurHPostProcess.onActivateObservable.add(function () {
  64345. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  64346. _this._blurHPostProcess.kernel = size * dw;
  64347. });
  64348. this._blurVPostProcess.onActivateObservable.add(function () {
  64349. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  64350. _this._blurVPostProcess.kernel = size * dw;
  64351. });
  64352. };
  64353. SSAORenderingPipeline.prototype._rebuild = function () {
  64354. this._firstUpdate = true;
  64355. _super.prototype._rebuild.call(this);
  64356. };
  64357. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  64358. var _this = this;
  64359. var numSamples = 16;
  64360. var sampleSphere = [
  64361. 0.5381, 0.1856, -0.4319,
  64362. 0.1379, 0.2486, 0.4430,
  64363. 0.3371, 0.5679, -0.0057,
  64364. -0.6999, -0.0451, -0.0019,
  64365. 0.0689, -0.1598, -0.8547,
  64366. 0.0560, 0.0069, -0.1843,
  64367. -0.0146, 0.1402, 0.0762,
  64368. 0.0100, -0.1924, -0.0344,
  64369. -0.3577, -0.5301, -0.4358,
  64370. -0.3169, 0.1063, 0.0158,
  64371. 0.0103, -0.5869, 0.0046,
  64372. -0.0897, -0.4940, 0.3287,
  64373. 0.7119, -0.0154, -0.0918,
  64374. -0.0533, 0.0596, -0.5411,
  64375. 0.0352, -0.0631, 0.5460,
  64376. -0.4776, 0.2847, -0.0271
  64377. ];
  64378. var samplesFactor = 1.0 / numSamples;
  64379. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  64380. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  64381. "area", "fallOff", "base", "range", "viewport"
  64382. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  64383. this._ssaoPostProcess.onApply = function (effect) {
  64384. if (_this._firstUpdate) {
  64385. effect.setArray3("sampleSphere", sampleSphere);
  64386. effect.setFloat("samplesFactor", samplesFactor);
  64387. effect.setFloat("randTextureTiles", 4.0);
  64388. }
  64389. effect.setFloat("totalStrength", _this.totalStrength);
  64390. effect.setFloat("radius", _this.radius);
  64391. effect.setFloat("area", _this.area);
  64392. effect.setFloat("fallOff", _this.fallOff);
  64393. effect.setFloat("base", _this.base);
  64394. effect.setTexture("textureSampler", _this._depthTexture);
  64395. effect.setTexture("randomSampler", _this._randomTexture);
  64396. };
  64397. };
  64398. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  64399. var _this = this;
  64400. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  64401. this._ssaoCombinePostProcess.onApply = function (effect) {
  64402. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  64403. };
  64404. };
  64405. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  64406. var size = 512;
  64407. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  64408. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64409. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64410. var context = this._randomTexture.getContext();
  64411. var rand = function (min, max) {
  64412. return Math.random() * (max - min) + min;
  64413. };
  64414. var randVector = BABYLON.Vector3.Zero();
  64415. for (var x = 0; x < size; x++) {
  64416. for (var y = 0; y < size; y++) {
  64417. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  64418. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  64419. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  64420. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  64421. context.fillRect(x, y, 1, 1);
  64422. }
  64423. }
  64424. this._randomTexture.update(false);
  64425. };
  64426. __decorate([
  64427. BABYLON.serialize()
  64428. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  64429. __decorate([
  64430. BABYLON.serialize()
  64431. ], SSAORenderingPipeline.prototype, "radius", void 0);
  64432. __decorate([
  64433. BABYLON.serialize()
  64434. ], SSAORenderingPipeline.prototype, "area", void 0);
  64435. __decorate([
  64436. BABYLON.serialize()
  64437. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  64438. __decorate([
  64439. BABYLON.serialize()
  64440. ], SSAORenderingPipeline.prototype, "base", void 0);
  64441. return SSAORenderingPipeline;
  64442. }(BABYLON.PostProcessRenderPipeline));
  64443. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  64444. })(BABYLON || (BABYLON = {}));
  64445. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  64446. var BABYLON;
  64447. (function (BABYLON) {
  64448. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  64449. __extends(SSAO2RenderingPipeline, _super);
  64450. /**
  64451. * @constructor
  64452. * @param {string} name - The rendering pipeline name
  64453. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  64454. * @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 }
  64455. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  64456. */
  64457. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  64458. var _this = _super.call(this, scene.getEngine(), name) || this;
  64459. // Members
  64460. /**
  64461. * The PassPostProcess id in the pipeline that contains the original scene color
  64462. * @type {string}
  64463. */
  64464. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  64465. /**
  64466. * The SSAO PostProcess id in the pipeline
  64467. * @type {string}
  64468. */
  64469. _this.SSAORenderEffect = "SSAORenderEffect";
  64470. /**
  64471. * The horizontal blur PostProcess id in the pipeline
  64472. * @type {string}
  64473. */
  64474. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  64475. /**
  64476. * The vertical blur PostProcess id in the pipeline
  64477. * @type {string}
  64478. */
  64479. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  64480. /**
  64481. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  64482. * @type {string}
  64483. */
  64484. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  64485. /**
  64486. * The output strength of the SSAO post-process. Default value is 1.0.
  64487. * @type {number}
  64488. */
  64489. _this.totalStrength = 1.0;
  64490. /**
  64491. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  64492. * @type {number}
  64493. */
  64494. _this.maxZ = 100.0;
  64495. /**
  64496. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  64497. * @type {number}
  64498. */
  64499. _this.minZAspect = 0.2;
  64500. /**
  64501. * Number of samples used for the SSAO calculations. Default value is 8
  64502. * @type {number}
  64503. */
  64504. _this._samples = 8;
  64505. /**
  64506. * Are we using bilateral blur ?
  64507. * @type {boolean}
  64508. */
  64509. _this._expensiveBlur = true;
  64510. /**
  64511. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  64512. * @type {number}
  64513. */
  64514. _this.radius = 2.0;
  64515. /**
  64516. * The base color of the SSAO post-process
  64517. * The final result is "base + ssao" between [0, 1]
  64518. * @type {number}
  64519. */
  64520. _this.base = 0.1;
  64521. _this._firstUpdate = true;
  64522. _this._scene = scene;
  64523. if (!_this.isSupported) {
  64524. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  64525. return _this;
  64526. }
  64527. var ssaoRatio = ratio.ssaoRatio || ratio;
  64528. var blurRatio = ratio.blurRatio || ratio;
  64529. // Set up assets
  64530. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  64531. _this._createRandomTexture();
  64532. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  64533. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  64534. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  64535. _this._createSSAOPostProcess(1.0);
  64536. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  64537. _this._createSSAOCombinePostProcess(blurRatio);
  64538. // Set up pipeline
  64539. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  64540. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  64541. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  64542. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  64543. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  64544. // Finish
  64545. scene.postProcessRenderPipelineManager.addPipeline(_this);
  64546. if (cameras)
  64547. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  64548. return _this;
  64549. }
  64550. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  64551. get: function () {
  64552. return this._samples;
  64553. },
  64554. set: function (n) {
  64555. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  64556. this._samples = n;
  64557. this._sampleSphere = this._generateHemisphere();
  64558. this._firstUpdate = true;
  64559. },
  64560. enumerable: true,
  64561. configurable: true
  64562. });
  64563. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  64564. get: function () {
  64565. return this._expensiveBlur;
  64566. },
  64567. set: function (b) {
  64568. 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"]);
  64569. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  64570. this._expensiveBlur = b;
  64571. this._firstUpdate = true;
  64572. },
  64573. enumerable: true,
  64574. configurable: true
  64575. });
  64576. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  64577. /**
  64578. * Support test.
  64579. * @type {boolean}
  64580. */
  64581. get: function () {
  64582. var engine = BABYLON.Engine.LastCreatedEngine;
  64583. if (!engine) {
  64584. return false;
  64585. }
  64586. return engine.getCaps().drawBuffersExtension;
  64587. },
  64588. enumerable: true,
  64589. configurable: true
  64590. });
  64591. // Public Methods
  64592. /**
  64593. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  64594. */
  64595. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  64596. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  64597. for (var i = 0; i < this._scene.cameras.length; i++) {
  64598. var camera = this._scene.cameras[i];
  64599. this._originalColorPostProcess.dispose(camera);
  64600. this._ssaoPostProcess.dispose(camera);
  64601. this._blurHPostProcess.dispose(camera);
  64602. this._blurVPostProcess.dispose(camera);
  64603. this._ssaoCombinePostProcess.dispose(camera);
  64604. }
  64605. this._randomTexture.dispose();
  64606. if (disableGeometryBufferRenderer)
  64607. this._scene.disableGeometryBufferRenderer();
  64608. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  64609. _super.prototype.dispose.call(this);
  64610. };
  64611. // Private Methods
  64612. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  64613. var _this = this;
  64614. this._samplerOffsets = [];
  64615. var expensive = this.expensiveBlur;
  64616. for (var i = -8; i < 8; i++) {
  64617. this._samplerOffsets.push(i * 2 + 0.5);
  64618. }
  64619. 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");
  64620. this._blurHPostProcess.onApply = function (effect) {
  64621. if (!_this._scene.activeCamera) {
  64622. return;
  64623. }
  64624. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  64625. effect.setFloat("near", _this._scene.activeCamera.minZ);
  64626. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  64627. effect.setFloat("radius", _this.radius);
  64628. effect.setTexture("depthSampler", _this._depthTexture);
  64629. if (_this._firstUpdate) {
  64630. effect.setArray("samplerOffsets", _this._samplerOffsets);
  64631. }
  64632. };
  64633. 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");
  64634. this._blurVPostProcess.onApply = function (effect) {
  64635. if (!_this._scene.activeCamera) {
  64636. return;
  64637. }
  64638. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  64639. effect.setFloat("near", _this._scene.activeCamera.minZ);
  64640. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  64641. effect.setFloat("radius", _this.radius);
  64642. effect.setTexture("depthSampler", _this._depthTexture);
  64643. if (_this._firstUpdate) {
  64644. effect.setArray("samplerOffsets", _this._samplerOffsets);
  64645. _this._firstUpdate = false;
  64646. }
  64647. };
  64648. };
  64649. SSAO2RenderingPipeline.prototype._rebuild = function () {
  64650. this._firstUpdate = true;
  64651. _super.prototype._rebuild.call(this);
  64652. };
  64653. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  64654. var numSamples = this.samples;
  64655. var result = [];
  64656. var vector, scale;
  64657. var rand = function (min, max) {
  64658. return Math.random() * (max - min) + min;
  64659. };
  64660. var i = 0;
  64661. while (i < numSamples) {
  64662. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  64663. vector.normalize();
  64664. scale = i / numSamples;
  64665. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  64666. vector.scaleInPlace(scale);
  64667. result.push(vector.x, vector.y, vector.z);
  64668. i++;
  64669. }
  64670. return result;
  64671. };
  64672. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  64673. var _this = this;
  64674. var numSamples = this.samples;
  64675. this._sampleSphere = this._generateHemisphere();
  64676. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  64677. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  64678. "base", "range", "projection", "near", "far", "texelSize",
  64679. "xViewport", "yViewport", "maxZ", "minZAspect"
  64680. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  64681. this._ssaoPostProcess.onApply = function (effect) {
  64682. if (_this._firstUpdate) {
  64683. effect.setArray3("sampleSphere", _this._sampleSphere);
  64684. effect.setFloat("randTextureTiles", 4.0);
  64685. }
  64686. if (!_this._scene.activeCamera) {
  64687. return;
  64688. }
  64689. effect.setFloat("samplesFactor", 1 / _this.samples);
  64690. effect.setFloat("totalStrength", _this.totalStrength);
  64691. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  64692. effect.setFloat("radius", _this.radius);
  64693. effect.setFloat("maxZ", _this.maxZ);
  64694. effect.setFloat("minZAspect", _this.minZAspect);
  64695. effect.setFloat("base", _this.base);
  64696. effect.setFloat("near", _this._scene.activeCamera.minZ);
  64697. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  64698. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  64699. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  64700. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  64701. effect.setTexture("textureSampler", _this._depthTexture);
  64702. effect.setTexture("normalSampler", _this._normalTexture);
  64703. effect.setTexture("randomSampler", _this._randomTexture);
  64704. };
  64705. };
  64706. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  64707. var _this = this;
  64708. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  64709. this._ssaoCombinePostProcess.onApply = function (effect) {
  64710. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  64711. };
  64712. };
  64713. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  64714. var size = 512;
  64715. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  64716. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64717. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64718. var context = this._randomTexture.getContext();
  64719. var rand = function (min, max) {
  64720. return Math.random() * (max - min) + min;
  64721. };
  64722. var randVector = BABYLON.Vector3.Zero();
  64723. for (var x = 0; x < size; x++) {
  64724. for (var y = 0; y < size; y++) {
  64725. randVector.x = rand(0.0, 1.0);
  64726. randVector.y = rand(0.0, 1.0);
  64727. randVector.z = 0.0;
  64728. randVector.normalize();
  64729. randVector.scaleInPlace(255);
  64730. randVector.x = Math.floor(randVector.x);
  64731. randVector.y = Math.floor(randVector.y);
  64732. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  64733. context.fillRect(x, y, 1, 1);
  64734. }
  64735. }
  64736. this._randomTexture.update(false);
  64737. };
  64738. __decorate([
  64739. BABYLON.serialize()
  64740. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  64741. __decorate([
  64742. BABYLON.serialize()
  64743. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  64744. __decorate([
  64745. BABYLON.serialize()
  64746. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  64747. __decorate([
  64748. BABYLON.serialize("samples")
  64749. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  64750. __decorate([
  64751. BABYLON.serialize("expensiveBlur")
  64752. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  64753. __decorate([
  64754. BABYLON.serialize()
  64755. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  64756. __decorate([
  64757. BABYLON.serialize()
  64758. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  64759. return SSAO2RenderingPipeline;
  64760. }(BABYLON.PostProcessRenderPipeline));
  64761. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  64762. })(BABYLON || (BABYLON = {}));
  64763. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  64764. // BABYLON.JS Chromatic Aberration GLSL Shader
  64765. // Author: Olivier Guyot
  64766. // Separates very slightly R, G and B colors on the edges of the screen
  64767. // Inspired by Francois Tarlier & Martins Upitis
  64768. var BABYLON;
  64769. (function (BABYLON) {
  64770. var LensRenderingPipeline = /** @class */ (function (_super) {
  64771. __extends(LensRenderingPipeline, _super);
  64772. /**
  64773. * @constructor
  64774. *
  64775. * Effect parameters are as follow:
  64776. * {
  64777. * chromatic_aberration: number; // from 0 to x (1 for realism)
  64778. * edge_blur: number; // from 0 to x (1 for realism)
  64779. * distortion: number; // from 0 to x (1 for realism)
  64780. * grain_amount: number; // from 0 to 1
  64781. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  64782. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  64783. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  64784. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  64785. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  64786. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  64787. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  64788. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  64789. * }
  64790. * Note: if an effect parameter is unset, effect is disabled
  64791. *
  64792. * @param {string} name - The rendering pipeline name
  64793. * @param {object} parameters - An object containing all parameters (see above)
  64794. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  64795. * @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)
  64796. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  64797. */
  64798. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  64799. if (ratio === void 0) { ratio = 1.0; }
  64800. var _this = _super.call(this, scene.getEngine(), name) || this;
  64801. // Lens effects can be of the following:
  64802. // - chromatic aberration (slight shift of RGB colors)
  64803. // - blur on the edge of the lens
  64804. // - lens distortion
  64805. // - depth-of-field blur & highlights enhancing
  64806. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  64807. // - grain effect (noise or custom texture)
  64808. // Two additional texture samplers are needed:
  64809. // - depth map (for depth-of-field)
  64810. // - grain texture
  64811. /**
  64812. * The chromatic aberration PostProcess id in the pipeline
  64813. * @type {string}
  64814. */
  64815. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  64816. /**
  64817. * The highlights enhancing PostProcess id in the pipeline
  64818. * @type {string}
  64819. */
  64820. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  64821. /**
  64822. * The depth-of-field PostProcess id in the pipeline
  64823. * @type {string}
  64824. */
  64825. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  64826. _this._scene = scene;
  64827. // Fetch texture samplers
  64828. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  64829. if (parameters.grain_texture) {
  64830. _this._grainTexture = parameters.grain_texture;
  64831. }
  64832. else {
  64833. _this._createGrainTexture();
  64834. }
  64835. // save parameters
  64836. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  64837. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  64838. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  64839. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  64840. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  64841. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  64842. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  64843. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  64844. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  64845. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  64846. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  64847. // Create effects
  64848. _this._createChromaticAberrationPostProcess(ratio);
  64849. _this._createHighlightsPostProcess(ratio);
  64850. _this._createDepthOfFieldPostProcess(ratio / 4);
  64851. // Set up pipeline
  64852. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  64853. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  64854. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  64855. if (_this._highlightsGain === -1) {
  64856. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  64857. }
  64858. // Finish
  64859. scene.postProcessRenderPipelineManager.addPipeline(_this);
  64860. if (cameras) {
  64861. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  64862. }
  64863. return _this;
  64864. }
  64865. // public methods (self explanatory)
  64866. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  64867. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  64868. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  64869. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  64870. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  64871. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  64872. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  64873. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  64874. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  64875. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  64876. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  64877. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  64878. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  64879. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  64880. };
  64881. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  64882. this._highlightsPostProcess.updateEffect();
  64883. };
  64884. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  64885. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  64886. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  64887. this._highlightsGain = amount;
  64888. };
  64889. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  64890. if (this._highlightsGain === -1) {
  64891. this._highlightsGain = 1.0;
  64892. }
  64893. this._highlightsThreshold = amount;
  64894. };
  64895. LensRenderingPipeline.prototype.disableHighlights = function () {
  64896. this._highlightsGain = -1;
  64897. };
  64898. /**
  64899. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  64900. */
  64901. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  64902. if (disableDepthRender === void 0) { disableDepthRender = false; }
  64903. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  64904. this._chromaticAberrationPostProcess = null;
  64905. this._highlightsPostProcess = null;
  64906. this._depthOfFieldPostProcess = null;
  64907. this._grainTexture.dispose();
  64908. if (disableDepthRender)
  64909. this._scene.disableDepthRenderer();
  64910. };
  64911. // colors shifting and distortion
  64912. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  64913. var _this = this;
  64914. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  64915. [], // samplers
  64916. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  64917. this._chromaticAberrationPostProcess.onApply = function (effect) {
  64918. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  64919. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  64920. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  64921. };
  64922. };
  64923. // highlights enhancing
  64924. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  64925. var _this = this;
  64926. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  64927. [], // samplers
  64928. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  64929. this._highlightsPostProcess.onApply = function (effect) {
  64930. effect.setFloat('gain', _this._highlightsGain);
  64931. effect.setFloat('threshold', _this._highlightsThreshold);
  64932. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  64933. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  64934. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  64935. };
  64936. };
  64937. // colors shifting and distortion
  64938. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  64939. var _this = this;
  64940. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  64941. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  64942. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  64943. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  64944. this._depthOfFieldPostProcess.onApply = function (effect) {
  64945. effect.setTexture("depthSampler", _this._depthTexture);
  64946. effect.setTexture("grainSampler", _this._grainTexture);
  64947. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  64948. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  64949. effect.setFloat('grain_amount', _this._grainAmount);
  64950. effect.setBool('blur_noise', _this._blurNoise);
  64951. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  64952. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  64953. effect.setFloat('distortion', _this._distortion);
  64954. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  64955. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  64956. effect.setFloat('aperture', _this._dofAperture);
  64957. effect.setFloat('darken', _this._dofDarken);
  64958. effect.setFloat('edge_blur', _this._edgeBlur);
  64959. effect.setBool('highlights', (_this._highlightsGain !== -1));
  64960. if (_this._scene.activeCamera) {
  64961. effect.setFloat('near', _this._scene.activeCamera.minZ);
  64962. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  64963. }
  64964. };
  64965. };
  64966. // creates a black and white random noise texture, 512x512
  64967. LensRenderingPipeline.prototype._createGrainTexture = function () {
  64968. var size = 512;
  64969. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64970. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64971. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64972. var context = this._grainTexture.getContext();
  64973. var rand = function (min, max) {
  64974. return Math.random() * (max - min) + min;
  64975. };
  64976. var value;
  64977. for (var x = 0; x < size; x++) {
  64978. for (var y = 0; y < size; y++) {
  64979. value = Math.floor(rand(0.42, 0.58) * 255);
  64980. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  64981. context.fillRect(x, y, 1, 1);
  64982. }
  64983. }
  64984. this._grainTexture.update(false);
  64985. };
  64986. return LensRenderingPipeline;
  64987. }(BABYLON.PostProcessRenderPipeline));
  64988. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  64989. })(BABYLON || (BABYLON = {}));
  64990. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  64991. var BABYLON;
  64992. (function (BABYLON) {
  64993. var StandardRenderingPipeline = /** @class */ (function (_super) {
  64994. __extends(StandardRenderingPipeline, _super);
  64995. /**
  64996. * @constructor
  64997. * @param {string} name - The rendering pipeline name
  64998. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  64999. * @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)
  65000. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  65001. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65002. */
  65003. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  65004. if (originalPostProcess === void 0) { originalPostProcess = null; }
  65005. var _this = _super.call(this, scene.getEngine(), name) || this;
  65006. _this.downSampleX4PostProcess = null;
  65007. _this.brightPassPostProcess = null;
  65008. _this.blurHPostProcesses = [];
  65009. _this.blurVPostProcesses = [];
  65010. _this.textureAdderPostProcess = null;
  65011. _this.volumetricLightPostProcess = null;
  65012. _this.volumetricLightSmoothXPostProcess = null;
  65013. _this.volumetricLightSmoothYPostProcess = null;
  65014. _this.volumetricLightMergePostProces = null;
  65015. _this.volumetricLightFinalPostProcess = null;
  65016. _this.luminancePostProcess = null;
  65017. _this.luminanceDownSamplePostProcesses = [];
  65018. _this.hdrPostProcess = null;
  65019. _this.textureAdderFinalPostProcess = null;
  65020. _this.lensFlareFinalPostProcess = null;
  65021. _this.hdrFinalPostProcess = null;
  65022. _this.lensFlarePostProcess = null;
  65023. _this.lensFlareComposePostProcess = null;
  65024. _this.motionBlurPostProcess = null;
  65025. _this.depthOfFieldPostProcess = null;
  65026. // Values
  65027. _this.brightThreshold = 1.0;
  65028. _this.blurWidth = 512.0;
  65029. _this.horizontalBlur = false;
  65030. _this.exposure = 1.0;
  65031. _this.lensTexture = null;
  65032. _this.volumetricLightCoefficient = 0.2;
  65033. _this.volumetricLightPower = 4.0;
  65034. _this.volumetricLightBlurScale = 64.0;
  65035. _this.sourceLight = null;
  65036. _this.hdrMinimumLuminance = 1.0;
  65037. _this.hdrDecreaseRate = 0.5;
  65038. _this.hdrIncreaseRate = 0.5;
  65039. _this.lensColorTexture = null;
  65040. _this.lensFlareStrength = 20.0;
  65041. _this.lensFlareGhostDispersal = 1.4;
  65042. _this.lensFlareHaloWidth = 0.7;
  65043. _this.lensFlareDistortionStrength = 16.0;
  65044. _this.lensStarTexture = null;
  65045. _this.lensFlareDirtTexture = null;
  65046. _this.depthOfFieldDistance = 10.0;
  65047. _this.depthOfFieldBlurWidth = 64.0;
  65048. _this.motionStrength = 1.0;
  65049. // IAnimatable
  65050. _this.animations = [];
  65051. _this._currentDepthOfFieldSource = null;
  65052. _this._hdrCurrentLuminance = 1.0;
  65053. // Getters and setters
  65054. _this._bloomEnabled = true;
  65055. _this._depthOfFieldEnabled = false;
  65056. _this._vlsEnabled = false;
  65057. _this._lensFlareEnabled = false;
  65058. _this._hdrEnabled = false;
  65059. _this._motionBlurEnabled = false;
  65060. _this._motionBlurSamples = 64.0;
  65061. _this._volumetricLightStepsCount = 50.0;
  65062. _this._cameras = cameras || [];
  65063. // Initialize
  65064. _this._scene = scene;
  65065. _this._basePostProcess = originalPostProcess;
  65066. _this._ratio = ratio;
  65067. // Misc
  65068. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65069. // Finish
  65070. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65071. _this._buildPipeline();
  65072. return _this;
  65073. }
  65074. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  65075. get: function () {
  65076. return this._bloomEnabled;
  65077. },
  65078. set: function (enabled) {
  65079. if (this._bloomEnabled === enabled) {
  65080. return;
  65081. }
  65082. this._bloomEnabled = enabled;
  65083. this._buildPipeline();
  65084. },
  65085. enumerable: true,
  65086. configurable: true
  65087. });
  65088. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  65089. get: function () {
  65090. return this._depthOfFieldEnabled;
  65091. },
  65092. set: function (enabled) {
  65093. if (this._depthOfFieldEnabled === enabled) {
  65094. return;
  65095. }
  65096. this._depthOfFieldEnabled = enabled;
  65097. this._buildPipeline();
  65098. },
  65099. enumerable: true,
  65100. configurable: true
  65101. });
  65102. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  65103. get: function () {
  65104. return this._lensFlareEnabled;
  65105. },
  65106. set: function (enabled) {
  65107. if (this._lensFlareEnabled === enabled) {
  65108. return;
  65109. }
  65110. this._lensFlareEnabled = enabled;
  65111. this._buildPipeline();
  65112. },
  65113. enumerable: true,
  65114. configurable: true
  65115. });
  65116. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  65117. get: function () {
  65118. return this._hdrEnabled;
  65119. },
  65120. set: function (enabled) {
  65121. if (this._hdrEnabled === enabled) {
  65122. return;
  65123. }
  65124. this._hdrEnabled = enabled;
  65125. this._buildPipeline();
  65126. },
  65127. enumerable: true,
  65128. configurable: true
  65129. });
  65130. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  65131. get: function () {
  65132. return this._vlsEnabled;
  65133. },
  65134. set: function (enabled) {
  65135. if (this._vlsEnabled === enabled) {
  65136. return;
  65137. }
  65138. if (enabled) {
  65139. var geometry = this._scene.enableGeometryBufferRenderer();
  65140. if (!geometry) {
  65141. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  65142. return;
  65143. }
  65144. }
  65145. this._vlsEnabled = enabled;
  65146. this._buildPipeline();
  65147. },
  65148. enumerable: true,
  65149. configurable: true
  65150. });
  65151. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  65152. get: function () {
  65153. return this._motionBlurEnabled;
  65154. },
  65155. set: function (enabled) {
  65156. if (this._motionBlurEnabled === enabled) {
  65157. return;
  65158. }
  65159. this._motionBlurEnabled = enabled;
  65160. this._buildPipeline();
  65161. },
  65162. enumerable: true,
  65163. configurable: true
  65164. });
  65165. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  65166. get: function () {
  65167. return this._volumetricLightStepsCount;
  65168. },
  65169. set: function (count) {
  65170. if (this.volumetricLightPostProcess) {
  65171. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  65172. }
  65173. this._volumetricLightStepsCount = count;
  65174. },
  65175. enumerable: true,
  65176. configurable: true
  65177. });
  65178. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  65179. get: function () {
  65180. return this._motionBlurSamples;
  65181. },
  65182. set: function (samples) {
  65183. if (this.motionBlurPostProcess) {
  65184. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  65185. }
  65186. this._motionBlurSamples = samples;
  65187. },
  65188. enumerable: true,
  65189. configurable: true
  65190. });
  65191. StandardRenderingPipeline.prototype._buildPipeline = function () {
  65192. var _this = this;
  65193. var ratio = this._ratio;
  65194. var scene = this._scene;
  65195. this._disposePostProcesses();
  65196. this._reset();
  65197. // Create pass post-process
  65198. if (!this._basePostProcess) {
  65199. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  65200. this.originalPostProcess.onApply = function (effect) {
  65201. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  65202. };
  65203. }
  65204. else {
  65205. this.originalPostProcess = this._basePostProcess;
  65206. }
  65207. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  65208. this._currentDepthOfFieldSource = this.originalPostProcess;
  65209. if (this._vlsEnabled) {
  65210. // Create volumetric light
  65211. this._createVolumetricLightPostProcess(scene, ratio);
  65212. // Create volumetric light final post-process
  65213. 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);
  65214. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  65215. }
  65216. if (this._bloomEnabled) {
  65217. // Create down sample X4 post-process
  65218. this._createDownSampleX4PostProcess(scene, ratio / 2);
  65219. // Create bright pass post-process
  65220. this._createBrightPassPostProcess(scene, ratio / 2);
  65221. // Create gaussian blur post-processes (down sampling blurs)
  65222. this._createBlurPostProcesses(scene, ratio / 4, 1);
  65223. // Create texture adder post-process
  65224. this._createTextureAdderPostProcess(scene, ratio);
  65225. // Create depth-of-field source post-process
  65226. 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);
  65227. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  65228. }
  65229. if (this._lensFlareEnabled) {
  65230. // Create lens flare post-process
  65231. this._createLensFlarePostProcess(scene, ratio);
  65232. // Create depth-of-field source post-process post lens-flare and disable it now
  65233. 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);
  65234. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  65235. }
  65236. if (this._hdrEnabled) {
  65237. // Create luminance
  65238. this._createLuminancePostProcesses(scene, this._floatTextureType);
  65239. // Create HDR
  65240. this._createHdrPostProcess(scene, ratio);
  65241. // Create depth-of-field source post-process post hdr and disable it now
  65242. 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);
  65243. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  65244. }
  65245. if (this._depthOfFieldEnabled) {
  65246. // Create gaussian blur used by depth-of-field
  65247. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  65248. // Create depth-of-field post-process
  65249. this._createDepthOfFieldPostProcess(scene, ratio);
  65250. }
  65251. if (this._motionBlurEnabled) {
  65252. // Create motion blur post-process
  65253. this._createMotionBlurPostProcess(scene, ratio);
  65254. }
  65255. if (this._cameras !== null) {
  65256. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  65257. }
  65258. };
  65259. // Down Sample X4 Post-Processs
  65260. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  65261. var _this = this;
  65262. var downSampleX4Offsets = new Array(32);
  65263. 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);
  65264. this.downSampleX4PostProcess.onApply = function (effect) {
  65265. var id = 0;
  65266. var width = _this.downSampleX4PostProcess.width;
  65267. var height = _this.downSampleX4PostProcess.height;
  65268. for (var i = -2; i < 2; i++) {
  65269. for (var j = -2; j < 2; j++) {
  65270. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  65271. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  65272. id += 2;
  65273. }
  65274. }
  65275. effect.setArray2("dsOffsets", downSampleX4Offsets);
  65276. };
  65277. // Add to pipeline
  65278. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  65279. };
  65280. // Brightpass Post-Process
  65281. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  65282. var _this = this;
  65283. var brightOffsets = new Array(8);
  65284. 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);
  65285. this.brightPassPostProcess.onApply = function (effect) {
  65286. var sU = (1.0 / _this.brightPassPostProcess.width);
  65287. var sV = (1.0 / _this.brightPassPostProcess.height);
  65288. brightOffsets[0] = -0.5 * sU;
  65289. brightOffsets[1] = 0.5 * sV;
  65290. brightOffsets[2] = 0.5 * sU;
  65291. brightOffsets[3] = 0.5 * sV;
  65292. brightOffsets[4] = -0.5 * sU;
  65293. brightOffsets[5] = -0.5 * sV;
  65294. brightOffsets[6] = 0.5 * sU;
  65295. brightOffsets[7] = -0.5 * sV;
  65296. effect.setArray2("dsOffsets", brightOffsets);
  65297. effect.setFloat("brightThreshold", _this.brightThreshold);
  65298. };
  65299. // Add to pipeline
  65300. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  65301. };
  65302. // Create blur H&V post-processes
  65303. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  65304. var _this = this;
  65305. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  65306. var engine = scene.getEngine();
  65307. 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);
  65308. 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);
  65309. blurX.onActivateObservable.add(function () {
  65310. var dw = blurX.width / engine.getRenderWidth();
  65311. blurX.kernel = _this[blurWidthKey] * dw;
  65312. });
  65313. blurY.onActivateObservable.add(function () {
  65314. var dw = blurY.height / engine.getRenderHeight();
  65315. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  65316. });
  65317. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  65318. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  65319. this.blurHPostProcesses.push(blurX);
  65320. this.blurVPostProcesses.push(blurY);
  65321. };
  65322. // Create texture adder post-process
  65323. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  65324. var _this = this;
  65325. 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);
  65326. this.textureAdderPostProcess.onApply = function (effect) {
  65327. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  65328. effect.setTexture("lensSampler", _this.lensTexture);
  65329. effect.setFloat("exposure", _this.exposure);
  65330. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  65331. };
  65332. // Add to pipeline
  65333. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  65334. };
  65335. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  65336. var _this = this;
  65337. var geometryRenderer = scene.enableGeometryBufferRenderer();
  65338. geometryRenderer.enablePosition = true;
  65339. var geometry = geometryRenderer.getGBuffer();
  65340. // Base post-process
  65341. 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));
  65342. var depthValues = BABYLON.Vector2.Zero();
  65343. this.volumetricLightPostProcess.onApply = function (effect) {
  65344. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  65345. var generator = _this.sourceLight.getShadowGenerator();
  65346. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  65347. effect.setTexture("positionSampler", geometry.textures[2]);
  65348. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  65349. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  65350. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  65351. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  65352. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  65353. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  65354. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  65355. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  65356. effect.setVector2("depthValues", depthValues);
  65357. }
  65358. };
  65359. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  65360. // Smooth
  65361. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  65362. // Merge
  65363. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  65364. this.volumetricLightMergePostProces.onApply = function (effect) {
  65365. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  65366. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  65367. };
  65368. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  65369. };
  65370. // Create luminance
  65371. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  65372. var _this = this;
  65373. // Create luminance
  65374. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  65375. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  65376. var offsets = [];
  65377. this.luminancePostProcess.onApply = function (effect) {
  65378. var sU = (1.0 / _this.luminancePostProcess.width);
  65379. var sV = (1.0 / _this.luminancePostProcess.height);
  65380. offsets[0] = -0.5 * sU;
  65381. offsets[1] = 0.5 * sV;
  65382. offsets[2] = 0.5 * sU;
  65383. offsets[3] = 0.5 * sV;
  65384. offsets[4] = -0.5 * sU;
  65385. offsets[5] = -0.5 * sV;
  65386. offsets[6] = 0.5 * sU;
  65387. offsets[7] = -0.5 * sV;
  65388. effect.setArray2("lumOffsets", offsets);
  65389. };
  65390. // Add to pipeline
  65391. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  65392. // Create down sample luminance
  65393. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  65394. var size = Math.pow(3, i);
  65395. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  65396. if (i === 0) {
  65397. defines += "#define FINAL_DOWN_SAMPLER";
  65398. }
  65399. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  65400. this.luminanceDownSamplePostProcesses.push(postProcess);
  65401. }
  65402. // Create callbacks and add effects
  65403. var lastLuminance = this.luminancePostProcess;
  65404. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  65405. var downSampleOffsets = new Array(18);
  65406. pp.onApply = function (effect) {
  65407. if (!lastLuminance) {
  65408. return;
  65409. }
  65410. var id = 0;
  65411. for (var x = -1; x < 2; x++) {
  65412. for (var y = -1; y < 2; y++) {
  65413. downSampleOffsets[id] = x / lastLuminance.width;
  65414. downSampleOffsets[id + 1] = y / lastLuminance.height;
  65415. id += 2;
  65416. }
  65417. }
  65418. effect.setArray2("dsOffsets", downSampleOffsets);
  65419. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  65420. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  65421. lastLuminance = _this.luminancePostProcess;
  65422. }
  65423. else {
  65424. lastLuminance = pp;
  65425. }
  65426. };
  65427. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  65428. pp.onAfterRender = function (effect) {
  65429. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  65430. 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);
  65431. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  65432. };
  65433. }
  65434. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  65435. });
  65436. };
  65437. // Create HDR post-process
  65438. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  65439. var _this = this;
  65440. 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);
  65441. var outputLiminance = 1;
  65442. var time = 0;
  65443. var lastTime = 0;
  65444. this.hdrPostProcess.onApply = function (effect) {
  65445. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  65446. time += scene.getEngine().getDeltaTime();
  65447. if (outputLiminance < 0) {
  65448. outputLiminance = _this._hdrCurrentLuminance;
  65449. }
  65450. else {
  65451. var dt = (lastTime - time) / 1000.0;
  65452. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  65453. outputLiminance += _this.hdrDecreaseRate * dt;
  65454. }
  65455. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  65456. outputLiminance -= _this.hdrIncreaseRate * dt;
  65457. }
  65458. else {
  65459. outputLiminance = _this._hdrCurrentLuminance;
  65460. }
  65461. }
  65462. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  65463. effect.setFloat("averageLuminance", outputLiminance);
  65464. lastTime = time;
  65465. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  65466. };
  65467. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  65468. };
  65469. // Create lens flare post-process
  65470. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  65471. var _this = this;
  65472. 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);
  65473. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  65474. this._createBlurPostProcesses(scene, ratio / 4, 2);
  65475. 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);
  65476. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  65477. var resolution = new BABYLON.Vector2(0, 0);
  65478. // Lens flare
  65479. this.lensFlarePostProcess.onApply = function (effect) {
  65480. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  65481. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  65482. effect.setFloat("strength", _this.lensFlareStrength);
  65483. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  65484. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  65485. // Shift
  65486. resolution.x = _this.lensFlarePostProcess.width;
  65487. resolution.y = _this.lensFlarePostProcess.height;
  65488. effect.setVector2("resolution", resolution);
  65489. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  65490. };
  65491. // Compose
  65492. 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);
  65493. 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);
  65494. this.lensFlareComposePostProcess.onApply = function (effect) {
  65495. if (!_this._scene.activeCamera) {
  65496. return;
  65497. }
  65498. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  65499. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  65500. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  65501. // Lens start rotation matrix
  65502. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  65503. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  65504. 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));
  65505. camRot *= 4.0;
  65506. 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);
  65507. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  65508. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  65509. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  65510. };
  65511. };
  65512. // Create depth-of-field post-process
  65513. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  65514. var _this = this;
  65515. 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);
  65516. this.depthOfFieldPostProcess.onApply = function (effect) {
  65517. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  65518. effect.setTexture("depthSampler", _this._getDepthTexture());
  65519. effect.setFloat("distance", _this.depthOfFieldDistance);
  65520. };
  65521. // Add to pipeline
  65522. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  65523. };
  65524. // Create motion blur post-process
  65525. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  65526. var _this = this;
  65527. 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);
  65528. var motionScale = 0;
  65529. var prevViewProjection = BABYLON.Matrix.Identity();
  65530. var invViewProjection = BABYLON.Matrix.Identity();
  65531. var viewProjection = BABYLON.Matrix.Identity();
  65532. var screenSize = BABYLON.Vector2.Zero();
  65533. this.motionBlurPostProcess.onApply = function (effect) {
  65534. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  65535. viewProjection.invertToRef(invViewProjection);
  65536. effect.setMatrix("inverseViewProjection", invViewProjection);
  65537. effect.setMatrix("prevViewProjection", prevViewProjection);
  65538. prevViewProjection = viewProjection;
  65539. screenSize.x = _this.motionBlurPostProcess.width;
  65540. screenSize.y = _this.motionBlurPostProcess.height;
  65541. effect.setVector2("screenSize", screenSize);
  65542. motionScale = scene.getEngine().getFps() / 60.0;
  65543. effect.setFloat("motionScale", motionScale);
  65544. effect.setFloat("motionStrength", _this.motionStrength);
  65545. effect.setTexture("depthSampler", _this._getDepthTexture());
  65546. };
  65547. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  65548. };
  65549. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  65550. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  65551. var renderer = this._scene.enableGeometryBufferRenderer();
  65552. return renderer.getGBuffer().textures[0];
  65553. }
  65554. return this._scene.enableDepthRenderer().getDepthMap();
  65555. };
  65556. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  65557. for (var i = 0; i < this._cameras.length; i++) {
  65558. var camera = this._cameras[i];
  65559. if (this.originalPostProcess) {
  65560. this.originalPostProcess.dispose(camera);
  65561. }
  65562. if (this.downSampleX4PostProcess) {
  65563. this.downSampleX4PostProcess.dispose(camera);
  65564. }
  65565. if (this.brightPassPostProcess) {
  65566. this.brightPassPostProcess.dispose(camera);
  65567. }
  65568. if (this.textureAdderPostProcess) {
  65569. this.textureAdderPostProcess.dispose(camera);
  65570. }
  65571. if (this.textureAdderFinalPostProcess) {
  65572. this.textureAdderFinalPostProcess.dispose(camera);
  65573. }
  65574. if (this.volumetricLightPostProcess) {
  65575. this.volumetricLightPostProcess.dispose(camera);
  65576. }
  65577. if (this.volumetricLightSmoothXPostProcess) {
  65578. this.volumetricLightSmoothXPostProcess.dispose(camera);
  65579. }
  65580. if (this.volumetricLightSmoothYPostProcess) {
  65581. this.volumetricLightSmoothYPostProcess.dispose(camera);
  65582. }
  65583. if (this.volumetricLightMergePostProces) {
  65584. this.volumetricLightMergePostProces.dispose(camera);
  65585. }
  65586. if (this.volumetricLightFinalPostProcess) {
  65587. this.volumetricLightFinalPostProcess.dispose(camera);
  65588. }
  65589. if (this.lensFlarePostProcess) {
  65590. this.lensFlarePostProcess.dispose(camera);
  65591. }
  65592. if (this.lensFlareComposePostProcess) {
  65593. this.lensFlareComposePostProcess.dispose(camera);
  65594. }
  65595. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  65596. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  65597. }
  65598. if (this.luminancePostProcess) {
  65599. this.luminancePostProcess.dispose(camera);
  65600. }
  65601. if (this.hdrPostProcess) {
  65602. this.hdrPostProcess.dispose(camera);
  65603. }
  65604. if (this.hdrFinalPostProcess) {
  65605. this.hdrFinalPostProcess.dispose(camera);
  65606. }
  65607. if (this.depthOfFieldPostProcess) {
  65608. this.depthOfFieldPostProcess.dispose(camera);
  65609. }
  65610. if (this.motionBlurPostProcess) {
  65611. this.motionBlurPostProcess.dispose(camera);
  65612. }
  65613. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  65614. this.blurHPostProcesses[j].dispose(camera);
  65615. }
  65616. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  65617. this.blurVPostProcesses[j].dispose(camera);
  65618. }
  65619. }
  65620. this.originalPostProcess = null;
  65621. this.downSampleX4PostProcess = null;
  65622. this.brightPassPostProcess = null;
  65623. this.textureAdderPostProcess = null;
  65624. this.textureAdderFinalPostProcess = null;
  65625. this.volumetricLightPostProcess = null;
  65626. this.volumetricLightSmoothXPostProcess = null;
  65627. this.volumetricLightSmoothYPostProcess = null;
  65628. this.volumetricLightMergePostProces = null;
  65629. this.volumetricLightFinalPostProcess = null;
  65630. this.lensFlarePostProcess = null;
  65631. this.lensFlareComposePostProcess = null;
  65632. this.luminancePostProcess = null;
  65633. this.hdrPostProcess = null;
  65634. this.hdrFinalPostProcess = null;
  65635. this.depthOfFieldPostProcess = null;
  65636. this.motionBlurPostProcess = null;
  65637. this.luminanceDownSamplePostProcesses = [];
  65638. this.blurHPostProcesses = [];
  65639. this.blurVPostProcesses = [];
  65640. };
  65641. // Dispose
  65642. StandardRenderingPipeline.prototype.dispose = function () {
  65643. this._disposePostProcesses();
  65644. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  65645. _super.prototype.dispose.call(this);
  65646. };
  65647. // Serialize rendering pipeline
  65648. StandardRenderingPipeline.prototype.serialize = function () {
  65649. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  65650. serializationObject.customType = "StandardRenderingPipeline";
  65651. return serializationObject;
  65652. };
  65653. /**
  65654. * Static members
  65655. */
  65656. // Parse serialized pipeline
  65657. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  65658. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  65659. };
  65660. // Luminance steps
  65661. StandardRenderingPipeline.LuminanceSteps = 6;
  65662. __decorate([
  65663. BABYLON.serialize()
  65664. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  65665. __decorate([
  65666. BABYLON.serialize()
  65667. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  65668. __decorate([
  65669. BABYLON.serialize()
  65670. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  65671. __decorate([
  65672. BABYLON.serialize()
  65673. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  65674. __decorate([
  65675. BABYLON.serializeAsTexture("lensTexture")
  65676. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  65677. __decorate([
  65678. BABYLON.serialize()
  65679. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  65680. __decorate([
  65681. BABYLON.serialize()
  65682. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  65683. __decorate([
  65684. BABYLON.serialize()
  65685. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  65686. __decorate([
  65687. BABYLON.serialize()
  65688. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  65689. __decorate([
  65690. BABYLON.serialize()
  65691. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  65692. __decorate([
  65693. BABYLON.serialize()
  65694. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  65695. __decorate([
  65696. BABYLON.serializeAsTexture("lensColorTexture")
  65697. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  65698. __decorate([
  65699. BABYLON.serialize()
  65700. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  65701. __decorate([
  65702. BABYLON.serialize()
  65703. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  65704. __decorate([
  65705. BABYLON.serialize()
  65706. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  65707. __decorate([
  65708. BABYLON.serialize()
  65709. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  65710. __decorate([
  65711. BABYLON.serializeAsTexture("lensStarTexture")
  65712. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  65713. __decorate([
  65714. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  65715. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  65716. __decorate([
  65717. BABYLON.serialize()
  65718. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  65719. __decorate([
  65720. BABYLON.serialize()
  65721. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  65722. __decorate([
  65723. BABYLON.serialize()
  65724. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  65725. __decorate([
  65726. BABYLON.serialize()
  65727. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  65728. __decorate([
  65729. BABYLON.serialize()
  65730. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  65731. __decorate([
  65732. BABYLON.serialize()
  65733. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  65734. __decorate([
  65735. BABYLON.serialize()
  65736. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  65737. __decorate([
  65738. BABYLON.serialize()
  65739. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  65740. __decorate([
  65741. BABYLON.serialize()
  65742. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  65743. __decorate([
  65744. BABYLON.serialize()
  65745. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  65746. __decorate([
  65747. BABYLON.serialize()
  65748. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  65749. __decorate([
  65750. BABYLON.serialize()
  65751. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  65752. return StandardRenderingPipeline;
  65753. }(BABYLON.PostProcessRenderPipeline));
  65754. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  65755. })(BABYLON || (BABYLON = {}));
  65756. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  65757. var BABYLON;
  65758. (function (BABYLON) {
  65759. var FxaaPostProcess = /** @class */ (function (_super) {
  65760. __extends(FxaaPostProcess, _super);
  65761. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  65762. if (camera === void 0) { camera = null; }
  65763. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65764. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  65765. _this.onApplyObservable.add(function (effect) {
  65766. var texelSize = _this.texelSize;
  65767. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  65768. });
  65769. return _this;
  65770. }
  65771. return FxaaPostProcess;
  65772. }(BABYLON.PostProcess));
  65773. BABYLON.FxaaPostProcess = FxaaPostProcess;
  65774. })(BABYLON || (BABYLON = {}));
  65775. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  65776. var BABYLON;
  65777. (function (BABYLON) {
  65778. /**
  65779. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  65780. */
  65781. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  65782. __extends(CircleOfConfusionPostProcess, _super);
  65783. /**
  65784. * Creates a new instance of @see CircleOfConfusionPostProcess
  65785. * @param name The name of the effect.
  65786. * @param scene The scene the effect belongs to.
  65787. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  65788. * @param options The required width/height ratio to downsize to before computing the render pass.
  65789. * @param camera The camera to apply the render pass to.
  65790. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65791. * @param engine The engine which the post process will be applied. (default: current engine)
  65792. * @param reusable If the post process can be reused on the same frame. (default: false)
  65793. * @param textureType Type of textures used when performing the post process. (default: 0)
  65794. */
  65795. function CircleOfConfusionPostProcess(name, scene, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  65796. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65797. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  65798. /**
  65799. * 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.
  65800. */
  65801. _this.lensSize = 50;
  65802. /**
  65803. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  65804. */
  65805. _this.fStop = 1.4;
  65806. /**
  65807. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  65808. */
  65809. _this.focusDistance = 2000;
  65810. /**
  65811. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  65812. */
  65813. _this.focalLength = 50;
  65814. _this.onApplyObservable.add(function (effect) {
  65815. effect.setTexture("depthSampler", depthTexture);
  65816. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  65817. var aperture = _this.lensSize / _this.fStop;
  65818. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  65819. effect.setFloat('focusDistance', _this.focusDistance);
  65820. effect.setFloat('cocPrecalculation', cocPrecalculation);
  65821. if (scene.activeCamera) {
  65822. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  65823. }
  65824. });
  65825. return _this;
  65826. }
  65827. return CircleOfConfusionPostProcess;
  65828. }(BABYLON.PostProcess));
  65829. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  65830. })(BABYLON || (BABYLON = {}));
  65831. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  65832. var BABYLON;
  65833. (function (BABYLON) {
  65834. /**
  65835. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  65836. */
  65837. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  65838. __extends(DepthOfFieldMergePostProcess, _super);
  65839. /**
  65840. * Creates a new instance of @see CircleOfConfusionPostProcess
  65841. * @param name The name of the effect.
  65842. * @param original The non-blurred image to be modified
  65843. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  65844. * @param options The required width/height ratio to downsize to before computing the render pass.
  65845. * @param camera The camera to apply the render pass to.
  65846. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65847. * @param engine The engine which the post process will be applied. (default: current engine)
  65848. * @param reusable If the post process can be reused on the same frame. (default: false)
  65849. * @param textureType Type of textures used when performing the post process. (default: 0)
  65850. */
  65851. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, options, camera, samplingMode, engine, reusable, textureType) {
  65852. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65853. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  65854. _this.onApplyObservable.add(function (effect) {
  65855. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  65856. effect.setTextureFromPostProcess("originalSampler", original);
  65857. });
  65858. return _this;
  65859. }
  65860. return DepthOfFieldMergePostProcess;
  65861. }(BABYLON.PostProcess));
  65862. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  65863. })(BABYLON || (BABYLON = {}));
  65864. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  65865. var BABYLON;
  65866. (function (BABYLON) {
  65867. /**
  65868. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  65869. */
  65870. var DepthOfFieldEffect = /** @class */ (function (_super) {
  65871. __extends(DepthOfFieldEffect, _super);
  65872. /**
  65873. * Creates a new instance of @see DepthOfFieldEffect
  65874. * @param scene The scene the effect belongs to.
  65875. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  65876. */
  65877. function DepthOfFieldEffect(scene, pipelineTextureType) {
  65878. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  65879. var _this = _super.call(this, scene.getEngine(), "depth of field", function () { return [_this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY, _this._depthOfFieldBlurX, _this._depthOfFieldMerge]; }, true) || this;
  65880. // Enable and get current depth map
  65881. var depthMap = scene.enableDepthRenderer().getDepthMap();
  65882. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  65883. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", scene, depthMap, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  65884. // Capture circle of confusion texture
  65885. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  65886. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  65887. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  65888. _this._depthOfFieldBlurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), 15, 1.0, null, depthMap, _this._circleOfConfusion, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  65889. _this._depthOfFieldBlurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), 15, 1.0, null, depthMap, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  65890. // Merge blurred images with original image based on circleOfConfusion
  65891. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  65892. return _this;
  65893. }
  65894. Object.defineProperty(DepthOfFieldEffect.prototype, "kernelSize", {
  65895. get: function () {
  65896. return this._depthOfFieldBlurX.kernel;
  65897. },
  65898. /**
  65899. * The size of the kernel to be used for the blur
  65900. */
  65901. set: function (value) {
  65902. this._depthOfFieldBlurX.kernel = value;
  65903. this._depthOfFieldBlurY.kernel = value;
  65904. },
  65905. enumerable: true,
  65906. configurable: true
  65907. });
  65908. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  65909. get: function () {
  65910. return this._circleOfConfusion.focalLength;
  65911. },
  65912. /**
  65913. * The focal the length of the camera used in the effect
  65914. */
  65915. set: function (value) {
  65916. this._circleOfConfusion.focalLength = value;
  65917. },
  65918. enumerable: true,
  65919. configurable: true
  65920. });
  65921. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  65922. get: function () {
  65923. return this._circleOfConfusion.fStop;
  65924. },
  65925. /**
  65926. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  65927. */
  65928. set: function (value) {
  65929. this._circleOfConfusion.fStop = value;
  65930. },
  65931. enumerable: true,
  65932. configurable: true
  65933. });
  65934. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  65935. get: function () {
  65936. return this._circleOfConfusion.focusDistance;
  65937. },
  65938. /**
  65939. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  65940. */
  65941. set: function (value) {
  65942. this._circleOfConfusion.focusDistance = value;
  65943. },
  65944. enumerable: true,
  65945. configurable: true
  65946. });
  65947. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  65948. get: function () {
  65949. return this._circleOfConfusion.lensSize;
  65950. },
  65951. /**
  65952. * 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.
  65953. */
  65954. set: function (value) {
  65955. this._circleOfConfusion.lensSize = value;
  65956. },
  65957. enumerable: true,
  65958. configurable: true
  65959. });
  65960. /**
  65961. * Disposes each of the internal effects for a given camera.
  65962. * @param camera The camera to dispose the effect on.
  65963. */
  65964. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  65965. this._depthOfFieldPass.dispose(camera);
  65966. this._circleOfConfusion.dispose(camera);
  65967. this._depthOfFieldBlurX.dispose(camera);
  65968. this._depthOfFieldBlurY.dispose(camera);
  65969. this._depthOfFieldMerge.dispose(camera);
  65970. };
  65971. return DepthOfFieldEffect;
  65972. }(BABYLON.PostProcessRenderEffect));
  65973. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  65974. })(BABYLON || (BABYLON = {}));
  65975. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  65976. var BABYLON;
  65977. (function (BABYLON) {
  65978. /**
  65979. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  65980. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  65981. */
  65982. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  65983. __extends(DefaultRenderingPipeline, _super);
  65984. /**
  65985. * @constructor
  65986. * @param {string} name - The rendering pipeline name
  65987. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65988. * @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)
  65989. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65990. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  65991. */
  65992. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  65993. if (automaticBuild === void 0) { automaticBuild = true; }
  65994. var _this = _super.call(this, scene.getEngine(), name) || this;
  65995. /**
  65996. * ID of the pass post process used for bloom,
  65997. */
  65998. _this.PassPostProcessId = "PassPostProcessEffect";
  65999. /**
  66000. * ID of the highlight post process used for bloom,
  66001. */
  66002. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  66003. /**
  66004. * ID of the blurX post process used for bloom,
  66005. */
  66006. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  66007. /**
  66008. * ID of the blurY post process used for bloom,
  66009. */
  66010. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  66011. /**
  66012. * ID of the copy back post process used for bloom,
  66013. */
  66014. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  66015. /**
  66016. * ID of the image processing post process;
  66017. */
  66018. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  66019. /**
  66020. * ID of the Fast Approximate Anti-Aliasing post process;
  66021. */
  66022. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  66023. /**
  66024. * ID of the final merge post process;
  66025. */
  66026. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  66027. /**
  66028. * Animations which can be used to tweak settings over a period of time
  66029. */
  66030. _this.animations = [];
  66031. // Values
  66032. _this._bloomEnabled = false;
  66033. _this._depthOfFieldEnabled = false;
  66034. _this._fxaaEnabled = false;
  66035. _this._imageProcessingEnabled = true;
  66036. _this._bloomScale = 0.6;
  66037. _this._buildAllowed = true;
  66038. /**
  66039. * Specifies the size of the bloom blur kernel, relative to the final output size
  66040. */
  66041. _this.bloomKernel = 64;
  66042. /**
  66043. * Specifies the weight of the bloom in the final rendering
  66044. */
  66045. _this._bloomWeight = 0.15;
  66046. _this._cameras = cameras || [];
  66047. _this._buildAllowed = automaticBuild;
  66048. // Initialize
  66049. _this._scene = scene;
  66050. var caps = _this._scene.getEngine().getCaps();
  66051. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  66052. // Misc
  66053. if (_this._hdr) {
  66054. if (caps.textureHalfFloatRender) {
  66055. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66056. }
  66057. else if (caps.textureFloatRender) {
  66058. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66059. }
  66060. }
  66061. else {
  66062. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66063. }
  66064. // Attach
  66065. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66066. _this._buildPipeline();
  66067. return _this;
  66068. }
  66069. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  66070. get: function () {
  66071. return this._bloomWeight;
  66072. },
  66073. /**
  66074. * The strength of the bloom.
  66075. */
  66076. set: function (value) {
  66077. if (this._bloomWeight === value) {
  66078. return;
  66079. }
  66080. this._bloomWeight = value;
  66081. if (this._hdr && this.copyBack) {
  66082. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  66083. }
  66084. },
  66085. enumerable: true,
  66086. configurable: true
  66087. });
  66088. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  66089. get: function () {
  66090. return this._bloomScale;
  66091. },
  66092. /**
  66093. * The scale of the bloom, lower value will provide better performance.
  66094. */
  66095. set: function (value) {
  66096. if (this._bloomScale === value) {
  66097. return;
  66098. }
  66099. this._bloomScale = value;
  66100. this._buildPipeline();
  66101. },
  66102. enumerable: true,
  66103. configurable: true
  66104. });
  66105. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  66106. get: function () {
  66107. return this._bloomEnabled;
  66108. },
  66109. /**
  66110. * Enable or disable the bloom from the pipeline
  66111. */
  66112. set: function (enabled) {
  66113. if (this._bloomEnabled === enabled) {
  66114. return;
  66115. }
  66116. this._bloomEnabled = enabled;
  66117. this._buildPipeline();
  66118. },
  66119. enumerable: true,
  66120. configurable: true
  66121. });
  66122. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  66123. /**
  66124. * If the depth of field is enabled.
  66125. */
  66126. get: function () {
  66127. return this._depthOfFieldEnabled;
  66128. },
  66129. set: function (enabled) {
  66130. if (this._depthOfFieldEnabled === enabled) {
  66131. return;
  66132. }
  66133. this._depthOfFieldEnabled = enabled;
  66134. this._buildPipeline();
  66135. },
  66136. enumerable: true,
  66137. configurable: true
  66138. });
  66139. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  66140. get: function () {
  66141. return this._fxaaEnabled;
  66142. },
  66143. /**
  66144. * If the anti aliasing is enabled.
  66145. */
  66146. set: function (enabled) {
  66147. if (this._fxaaEnabled === enabled) {
  66148. return;
  66149. }
  66150. this._fxaaEnabled = enabled;
  66151. this._buildPipeline();
  66152. },
  66153. enumerable: true,
  66154. configurable: true
  66155. });
  66156. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  66157. get: function () {
  66158. return this._imageProcessingEnabled;
  66159. },
  66160. /**
  66161. * If image processing is enabled.
  66162. */
  66163. set: function (enabled) {
  66164. if (this._imageProcessingEnabled === enabled) {
  66165. return;
  66166. }
  66167. this._imageProcessingEnabled = enabled;
  66168. this._buildPipeline();
  66169. },
  66170. enumerable: true,
  66171. configurable: true
  66172. });
  66173. /**
  66174. * Force the compilation of the entire pipeline.
  66175. */
  66176. DefaultRenderingPipeline.prototype.prepare = function () {
  66177. var previousState = this._buildAllowed;
  66178. this._buildAllowed = true;
  66179. this._buildPipeline();
  66180. this._buildAllowed = previousState;
  66181. };
  66182. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  66183. var _this = this;
  66184. if (!this._buildAllowed) {
  66185. return;
  66186. }
  66187. var engine = this._scene.getEngine();
  66188. this._disposePostProcesses();
  66189. this._reset();
  66190. if (this.bloomEnabled) {
  66191. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66192. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  66193. if (!this._hdr) {
  66194. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66195. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  66196. this.highlights.autoClear = false;
  66197. this.highlights.alwaysForcePOT = true;
  66198. }
  66199. 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);
  66200. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  66201. this.blurX.alwaysForcePOT = true;
  66202. this.blurX.autoClear = false;
  66203. this.blurX.onActivateObservable.add(function () {
  66204. var dw = _this.blurX.width / engine.getRenderWidth(true);
  66205. _this.blurX.kernel = _this.bloomKernel * dw;
  66206. });
  66207. 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);
  66208. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  66209. this.blurY.alwaysForcePOT = true;
  66210. this.blurY.autoClear = false;
  66211. this.blurY.onActivateObservable.add(function () {
  66212. var dh = _this.blurY.height / engine.getRenderHeight(true);
  66213. _this.blurY.kernel = _this.bloomKernel * dh;
  66214. });
  66215. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66216. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  66217. this.copyBack.alwaysForcePOT = true;
  66218. if (this._hdr) {
  66219. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  66220. var w = this.bloomWeight;
  66221. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  66222. }
  66223. else {
  66224. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  66225. }
  66226. this.copyBack.autoClear = false;
  66227. }
  66228. if (this.depthOfFieldEnabled) {
  66229. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, this._defaultPipelineTextureType);
  66230. this.addEffect(this.depthOfField);
  66231. }
  66232. if (this._imageProcessingEnabled) {
  66233. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66234. if (this._hdr) {
  66235. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  66236. }
  66237. else {
  66238. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  66239. }
  66240. }
  66241. if (this.fxaaEnabled) {
  66242. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66243. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  66244. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  66245. }
  66246. else if (this._hdr && this.imageProcessing) {
  66247. this.finalMerge = this.imageProcessing;
  66248. }
  66249. else {
  66250. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66251. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  66252. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  66253. }
  66254. if (this.bloomEnabled) {
  66255. if (this._hdr) {
  66256. this.copyBack.shareOutputWith(this.blurX);
  66257. if (this.imageProcessing) {
  66258. this.imageProcessing.shareOutputWith(this.pass);
  66259. this.imageProcessing.autoClear = false;
  66260. }
  66261. else if (this.fxaa) {
  66262. this.fxaa.shareOutputWith(this.pass);
  66263. }
  66264. else {
  66265. this.finalMerge.shareOutputWith(this.pass);
  66266. }
  66267. }
  66268. else {
  66269. if (this.fxaa) {
  66270. this.fxaa.shareOutputWith(this.pass);
  66271. }
  66272. else {
  66273. this.finalMerge.shareOutputWith(this.pass);
  66274. }
  66275. }
  66276. }
  66277. if (this._cameras !== null) {
  66278. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  66279. }
  66280. };
  66281. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  66282. for (var i = 0; i < this._cameras.length; i++) {
  66283. var camera = this._cameras[i];
  66284. if (this.pass) {
  66285. this.pass.dispose(camera);
  66286. }
  66287. if (this.highlights) {
  66288. this.highlights.dispose(camera);
  66289. }
  66290. if (this.blurX) {
  66291. this.blurX.dispose(camera);
  66292. }
  66293. if (this.blurY) {
  66294. this.blurY.dispose(camera);
  66295. }
  66296. if (this.copyBack) {
  66297. this.copyBack.dispose(camera);
  66298. }
  66299. if (this.imageProcessing) {
  66300. this.imageProcessing.dispose(camera);
  66301. }
  66302. if (this.fxaa) {
  66303. this.fxaa.dispose(camera);
  66304. }
  66305. if (this.finalMerge) {
  66306. this.finalMerge.dispose(camera);
  66307. }
  66308. if (this.depthOfField) {
  66309. this.depthOfField.disposeEffects(camera);
  66310. }
  66311. }
  66312. this.pass = null;
  66313. this.highlights = null;
  66314. this.blurX = null;
  66315. this.blurY = null;
  66316. this.copyBack = null;
  66317. this.imageProcessing = null;
  66318. this.fxaa = null;
  66319. this.finalMerge = null;
  66320. this.depthOfField = null;
  66321. };
  66322. /**
  66323. * Dispose of the pipeline and stop all post processes
  66324. */
  66325. DefaultRenderingPipeline.prototype.dispose = function () {
  66326. this._disposePostProcesses();
  66327. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  66328. _super.prototype.dispose.call(this);
  66329. };
  66330. /**
  66331. * Serialize the rendering pipeline (Used when exporting)
  66332. * @returns the serialized object
  66333. */
  66334. DefaultRenderingPipeline.prototype.serialize = function () {
  66335. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  66336. serializationObject.customType = "DefaultRenderingPipeline";
  66337. return serializationObject;
  66338. };
  66339. /**
  66340. * Parse the serialized pipeline
  66341. * @param source Source pipeline.
  66342. * @param scene The scene to load the pipeline to.
  66343. * @param rootUrl The URL of the serialized pipeline.
  66344. * @returns An instantiated pipeline from the serialized object.
  66345. */
  66346. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  66347. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  66348. };
  66349. __decorate([
  66350. BABYLON.serialize()
  66351. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  66352. __decorate([
  66353. BABYLON.serialize()
  66354. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  66355. __decorate([
  66356. BABYLON.serialize()
  66357. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  66358. __decorate([
  66359. BABYLON.serialize()
  66360. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  66361. __decorate([
  66362. BABYLON.serialize()
  66363. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  66364. __decorate([
  66365. BABYLON.serialize()
  66366. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  66367. __decorate([
  66368. BABYLON.serialize()
  66369. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  66370. __decorate([
  66371. BABYLON.serialize()
  66372. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  66373. __decorate([
  66374. BABYLON.serialize()
  66375. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  66376. return DefaultRenderingPipeline;
  66377. }(BABYLON.PostProcessRenderPipeline));
  66378. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  66379. })(BABYLON || (BABYLON = {}));
  66380. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  66381. var BABYLON;
  66382. (function (BABYLON) {
  66383. /**
  66384. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  66385. */
  66386. var GeometryBufferRenderer = /** @class */ (function () {
  66387. /**
  66388. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  66389. * @param scene The scene the buffer belongs to
  66390. * @param ratio How big is the buffer related to the main canvas.
  66391. */
  66392. function GeometryBufferRenderer(scene, ratio) {
  66393. if (ratio === void 0) { ratio = 1; }
  66394. this._enablePosition = false;
  66395. this._scene = scene;
  66396. this._ratio = ratio;
  66397. // Render target
  66398. this._createRenderTargets();
  66399. }
  66400. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  66401. /**
  66402. * Set the render list (meshes to be rendered) used in the G buffer.
  66403. */
  66404. set: function (meshes) {
  66405. this._multiRenderTarget.renderList = meshes;
  66406. },
  66407. enumerable: true,
  66408. configurable: true
  66409. });
  66410. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  66411. /**
  66412. * Gets wether or not G buffer are supported by the running hardware.
  66413. * This requires draw buffer supports
  66414. */
  66415. get: function () {
  66416. return this._multiRenderTarget.isSupported;
  66417. },
  66418. enumerable: true,
  66419. configurable: true
  66420. });
  66421. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  66422. /**
  66423. * Gets wether or not position are enabled for the G buffer.
  66424. */
  66425. get: function () {
  66426. return this._enablePosition;
  66427. },
  66428. /**
  66429. * Sets wether or not position are enabled for the G buffer.
  66430. */
  66431. set: function (enable) {
  66432. this._enablePosition = enable;
  66433. this.dispose();
  66434. this._createRenderTargets();
  66435. },
  66436. enumerable: true,
  66437. configurable: true
  66438. });
  66439. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  66440. /**
  66441. * Gets the scene associated with the buffer.
  66442. */
  66443. get: function () {
  66444. return this._scene;
  66445. },
  66446. enumerable: true,
  66447. configurable: true
  66448. });
  66449. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  66450. /**
  66451. * Gets the ratio used by the buffer during its creation.
  66452. * How big is the buffer related to the main canvas.
  66453. */
  66454. get: function () {
  66455. return this._ratio;
  66456. },
  66457. enumerable: true,
  66458. configurable: true
  66459. });
  66460. /**
  66461. * Checks wether everything is ready to render a submesh to the G buffer.
  66462. * @param subMesh the submesh to check readiness for
  66463. * @param useInstances is the mesh drawn using instance or not
  66464. * @returns true if ready otherwise false
  66465. */
  66466. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  66467. var material = subMesh.getMaterial();
  66468. if (material && material.disableDepthWrite) {
  66469. return false;
  66470. }
  66471. var defines = [];
  66472. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  66473. var mesh = subMesh.getMesh();
  66474. // Alpha test
  66475. if (material && material.needAlphaTesting()) {
  66476. defines.push("#define ALPHATEST");
  66477. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66478. attribs.push(BABYLON.VertexBuffer.UVKind);
  66479. defines.push("#define UV1");
  66480. }
  66481. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66482. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66483. defines.push("#define UV2");
  66484. }
  66485. }
  66486. // Buffers
  66487. if (this._enablePosition) {
  66488. defines.push("#define POSITION");
  66489. }
  66490. // Bones
  66491. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66492. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66493. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66494. if (mesh.numBoneInfluencers > 4) {
  66495. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66496. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66497. }
  66498. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66499. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  66500. }
  66501. else {
  66502. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66503. }
  66504. // Instances
  66505. if (useInstances) {
  66506. defines.push("#define INSTANCES");
  66507. attribs.push("world0");
  66508. attribs.push("world1");
  66509. attribs.push("world2");
  66510. attribs.push("world3");
  66511. }
  66512. // Get correct effect
  66513. var join = defines.join("\n");
  66514. if (this._cachedDefines !== join) {
  66515. this._cachedDefines = join;
  66516. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  66517. }
  66518. return this._effect.isReady();
  66519. };
  66520. /**
  66521. * Gets the current underlying G Buffer.
  66522. * @returns the buffer
  66523. */
  66524. GeometryBufferRenderer.prototype.getGBuffer = function () {
  66525. return this._multiRenderTarget;
  66526. };
  66527. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  66528. /**
  66529. * Gets the number of samples used to render the buffer (anti aliasing).
  66530. */
  66531. get: function () {
  66532. return this._multiRenderTarget.samples;
  66533. },
  66534. /**
  66535. * Sets the number of samples used to render the buffer (anti aliasing).
  66536. */
  66537. set: function (value) {
  66538. this._multiRenderTarget.samples = value;
  66539. },
  66540. enumerable: true,
  66541. configurable: true
  66542. });
  66543. /**
  66544. * Disposes the renderer and frees up associated resources.
  66545. */
  66546. GeometryBufferRenderer.prototype.dispose = function () {
  66547. this.getGBuffer().dispose();
  66548. };
  66549. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  66550. var _this = this;
  66551. var engine = this._scene.getEngine();
  66552. var count = this._enablePosition ? 3 : 2;
  66553. 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 });
  66554. if (!this.isSupported) {
  66555. return;
  66556. }
  66557. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66558. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66559. this._multiRenderTarget.refreshRate = 1;
  66560. this._multiRenderTarget.renderParticles = false;
  66561. this._multiRenderTarget.renderList = null;
  66562. // set default depth value to 1.0 (far away)
  66563. this._multiRenderTarget.onClearObservable.add(function (engine) {
  66564. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  66565. });
  66566. // Custom render function
  66567. var renderSubMesh = function (subMesh) {
  66568. var mesh = subMesh.getRenderingMesh();
  66569. var scene = _this._scene;
  66570. var engine = scene.getEngine();
  66571. var material = subMesh.getMaterial();
  66572. if (!material) {
  66573. return;
  66574. }
  66575. // Culling
  66576. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  66577. // Managing instances
  66578. var batch = mesh._getInstancesRenderList(subMesh._id);
  66579. if (batch.mustReturn) {
  66580. return;
  66581. }
  66582. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  66583. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  66584. engine.enableEffect(_this._effect);
  66585. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  66586. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  66587. _this._effect.setMatrix("view", scene.getViewMatrix());
  66588. // Alpha test
  66589. if (material && material.needAlphaTesting()) {
  66590. var alphaTexture = material.getAlphaTestTexture();
  66591. if (alphaTexture) {
  66592. _this._effect.setTexture("diffuseSampler", alphaTexture);
  66593. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  66594. }
  66595. }
  66596. // Bones
  66597. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  66598. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  66599. }
  66600. // Draw
  66601. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66602. }
  66603. };
  66604. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66605. var index;
  66606. if (depthOnlySubMeshes.length) {
  66607. engine.setColorWrite(false);
  66608. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66609. renderSubMesh(depthOnlySubMeshes.data[index]);
  66610. }
  66611. engine.setColorWrite(true);
  66612. }
  66613. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66614. renderSubMesh(opaqueSubMeshes.data[index]);
  66615. }
  66616. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66617. renderSubMesh(alphaTestSubMeshes.data[index]);
  66618. }
  66619. };
  66620. };
  66621. return GeometryBufferRenderer;
  66622. }());
  66623. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  66624. })(BABYLON || (BABYLON = {}));
  66625. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  66626. var BABYLON;
  66627. (function (BABYLON) {
  66628. var RefractionPostProcess = /** @class */ (function (_super) {
  66629. __extends(RefractionPostProcess, _super);
  66630. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  66631. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  66632. _this.color = color;
  66633. _this.depth = depth;
  66634. _this.colorLevel = colorLevel;
  66635. _this.onActivateObservable.add(function (cam) {
  66636. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  66637. });
  66638. _this.onApplyObservable.add(function (effect) {
  66639. effect.setColor3("baseColor", _this.color);
  66640. effect.setFloat("depth", _this.depth);
  66641. effect.setFloat("colorLevel", _this.colorLevel);
  66642. effect.setTexture("refractionSampler", _this._refRexture);
  66643. });
  66644. return _this;
  66645. }
  66646. // Methods
  66647. RefractionPostProcess.prototype.dispose = function (camera) {
  66648. if (this._refRexture) {
  66649. this._refRexture.dispose();
  66650. }
  66651. _super.prototype.dispose.call(this, camera);
  66652. };
  66653. return RefractionPostProcess;
  66654. }(BABYLON.PostProcess));
  66655. BABYLON.RefractionPostProcess = RefractionPostProcess;
  66656. })(BABYLON || (BABYLON = {}));
  66657. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  66658. var BABYLON;
  66659. (function (BABYLON) {
  66660. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  66661. __extends(BlackAndWhitePostProcess, _super);
  66662. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  66663. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  66664. _this.degree = 1;
  66665. _this.onApplyObservable.add(function (effect) {
  66666. effect.setFloat("degree", _this.degree);
  66667. });
  66668. return _this;
  66669. }
  66670. return BlackAndWhitePostProcess;
  66671. }(BABYLON.PostProcess));
  66672. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  66673. })(BABYLON || (BABYLON = {}));
  66674. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  66675. var BABYLON;
  66676. (function (BABYLON) {
  66677. var ConvolutionPostProcess = /** @class */ (function (_super) {
  66678. __extends(ConvolutionPostProcess, _super);
  66679. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  66680. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  66681. _this.kernel = kernel;
  66682. _this.onApply = function (effect) {
  66683. effect.setFloat2("screenSize", _this.width, _this.height);
  66684. effect.setArray("kernel", _this.kernel);
  66685. };
  66686. return _this;
  66687. }
  66688. // Statics
  66689. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  66690. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  66691. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  66692. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  66693. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  66694. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  66695. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  66696. return ConvolutionPostProcess;
  66697. }(BABYLON.PostProcess));
  66698. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  66699. })(BABYLON || (BABYLON = {}));
  66700. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  66701. var BABYLON;
  66702. (function (BABYLON) {
  66703. var FilterPostProcess = /** @class */ (function (_super) {
  66704. __extends(FilterPostProcess, _super);
  66705. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  66706. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  66707. _this.kernelMatrix = kernelMatrix;
  66708. _this.onApply = function (effect) {
  66709. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  66710. };
  66711. return _this;
  66712. }
  66713. return FilterPostProcess;
  66714. }(BABYLON.PostProcess));
  66715. BABYLON.FilterPostProcess = FilterPostProcess;
  66716. })(BABYLON || (BABYLON = {}));
  66717. //# sourceMappingURL=babylon.filterPostProcess.js.map
  66718. var BABYLON;
  66719. (function (BABYLON) {
  66720. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  66721. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  66722. __extends(VolumetricLightScatteringPostProcess, _super);
  66723. /**
  66724. * @constructor
  66725. * @param {string} name - The post-process name
  66726. * @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)
  66727. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  66728. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  66729. * @param {number} samples - The post-process quality, default 100
  66730. * @param {number} samplingMode - The post-process filtering mode
  66731. * @param {BABYLON.Engine} engine - The babylon engine
  66732. * @param {boolean} reusable - If the post-process is reusable
  66733. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  66734. */
  66735. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  66736. if (samples === void 0) { samples = 100; }
  66737. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  66738. 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;
  66739. _this._screenCoordinates = BABYLON.Vector2.Zero();
  66740. /**
  66741. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  66742. * @type {Vector3}
  66743. */
  66744. _this.customMeshPosition = BABYLON.Vector3.Zero();
  66745. /**
  66746. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  66747. * @type {boolean}
  66748. */
  66749. _this.useCustomMeshPosition = false;
  66750. /**
  66751. * If the post-process should inverse the light scattering direction
  66752. * @type {boolean}
  66753. */
  66754. _this.invert = true;
  66755. /**
  66756. * Array containing the excluded meshes not rendered in the internal pass
  66757. */
  66758. _this.excludedMeshes = new Array();
  66759. /**
  66760. * Controls the overall intensity of the post-process
  66761. * @type {number}
  66762. */
  66763. _this.exposure = 0.3;
  66764. /**
  66765. * Dissipates each sample's contribution in range [0, 1]
  66766. * @type {number}
  66767. */
  66768. _this.decay = 0.96815;
  66769. /**
  66770. * Controls the overall intensity of each sample
  66771. * @type {number}
  66772. */
  66773. _this.weight = 0.58767;
  66774. /**
  66775. * Controls the density of each sample
  66776. * @type {number}
  66777. */
  66778. _this.density = 0.926;
  66779. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  66780. engine = scene.getEngine();
  66781. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  66782. // Configure mesh
  66783. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  66784. // Configure
  66785. _this._createPass(scene, ratio.passRatio || ratio);
  66786. _this.onActivate = function (camera) {
  66787. if (!_this.isSupported) {
  66788. _this.dispose(camera);
  66789. }
  66790. _this.onActivate = null;
  66791. };
  66792. _this.onApplyObservable.add(function (effect) {
  66793. _this._updateMeshScreenCoordinates(scene);
  66794. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  66795. effect.setFloat("exposure", _this.exposure);
  66796. effect.setFloat("decay", _this.decay);
  66797. effect.setFloat("weight", _this.weight);
  66798. effect.setFloat("density", _this.density);
  66799. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  66800. });
  66801. return _this;
  66802. }
  66803. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  66804. get: function () {
  66805. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  66806. return false;
  66807. },
  66808. set: function (useDiffuseColor) {
  66809. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  66810. },
  66811. enumerable: true,
  66812. configurable: true
  66813. });
  66814. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  66815. return "VolumetricLightScatteringPostProcess";
  66816. };
  66817. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  66818. var mesh = subMesh.getMesh();
  66819. // Render this.mesh as default
  66820. if (mesh === this.mesh && mesh.material) {
  66821. return mesh.material.isReady(mesh);
  66822. }
  66823. var defines = [];
  66824. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66825. var material = subMesh.getMaterial();
  66826. // Alpha test
  66827. if (material) {
  66828. if (material.needAlphaTesting()) {
  66829. defines.push("#define ALPHATEST");
  66830. }
  66831. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66832. attribs.push(BABYLON.VertexBuffer.UVKind);
  66833. defines.push("#define UV1");
  66834. }
  66835. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66836. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66837. defines.push("#define UV2");
  66838. }
  66839. }
  66840. // Bones
  66841. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66842. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66843. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66844. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66845. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  66846. }
  66847. else {
  66848. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66849. }
  66850. // Instances
  66851. if (useInstances) {
  66852. defines.push("#define INSTANCES");
  66853. attribs.push("world0");
  66854. attribs.push("world1");
  66855. attribs.push("world2");
  66856. attribs.push("world3");
  66857. }
  66858. // Get correct effect
  66859. var join = defines.join("\n");
  66860. if (this._cachedDefines !== join) {
  66861. this._cachedDefines = join;
  66862. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  66863. }
  66864. return this._volumetricLightScatteringPass.isReady();
  66865. };
  66866. /**
  66867. * Sets the new light position for light scattering effect
  66868. * @param {BABYLON.Vector3} The new custom light position
  66869. */
  66870. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  66871. this.customMeshPosition = position;
  66872. };
  66873. /**
  66874. * Returns the light position for light scattering effect
  66875. * @return {BABYLON.Vector3} The custom light position
  66876. */
  66877. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  66878. return this.customMeshPosition;
  66879. };
  66880. /**
  66881. * Disposes the internal assets and detaches the post-process from the camera
  66882. */
  66883. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  66884. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  66885. if (rttIndex !== -1) {
  66886. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  66887. }
  66888. this._volumetricLightScatteringRTT.dispose();
  66889. _super.prototype.dispose.call(this, camera);
  66890. };
  66891. /**
  66892. * Returns the render target texture used by the post-process
  66893. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  66894. */
  66895. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  66896. return this._volumetricLightScatteringRTT;
  66897. };
  66898. // Private methods
  66899. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  66900. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  66901. return true;
  66902. }
  66903. return false;
  66904. };
  66905. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  66906. var _this = this;
  66907. var engine = scene.getEngine();
  66908. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  66909. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66910. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66911. this._volumetricLightScatteringRTT.renderList = null;
  66912. this._volumetricLightScatteringRTT.renderParticles = false;
  66913. var camera = this.getCamera();
  66914. if (camera) {
  66915. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  66916. }
  66917. else {
  66918. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  66919. }
  66920. // Custom render function for submeshes
  66921. var renderSubMesh = function (subMesh) {
  66922. var mesh = subMesh.getRenderingMesh();
  66923. if (_this._meshExcluded(mesh)) {
  66924. return;
  66925. }
  66926. var material = subMesh.getMaterial();
  66927. if (!material) {
  66928. return;
  66929. }
  66930. var scene = mesh.getScene();
  66931. var engine = scene.getEngine();
  66932. // Culling
  66933. engine.setState(material.backFaceCulling);
  66934. // Managing instances
  66935. var batch = mesh._getInstancesRenderList(subMesh._id);
  66936. if (batch.mustReturn) {
  66937. return;
  66938. }
  66939. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  66940. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  66941. var effect = _this._volumetricLightScatteringPass;
  66942. if (mesh === _this.mesh) {
  66943. if (subMesh.effect) {
  66944. effect = subMesh.effect;
  66945. }
  66946. else {
  66947. effect = material.getEffect();
  66948. }
  66949. }
  66950. engine.enableEffect(effect);
  66951. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  66952. if (mesh === _this.mesh) {
  66953. material.bind(mesh.getWorldMatrix(), mesh);
  66954. }
  66955. else {
  66956. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  66957. // Alpha test
  66958. if (material && material.needAlphaTesting()) {
  66959. var alphaTexture = material.getAlphaTestTexture();
  66960. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  66961. if (alphaTexture) {
  66962. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  66963. }
  66964. }
  66965. // Bones
  66966. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  66967. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  66968. }
  66969. }
  66970. // Draw
  66971. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  66972. }
  66973. };
  66974. // Render target texture callbacks
  66975. var savedSceneClearColor;
  66976. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  66977. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  66978. savedSceneClearColor = scene.clearColor;
  66979. scene.clearColor = sceneClearColor;
  66980. });
  66981. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  66982. scene.clearColor = savedSceneClearColor;
  66983. });
  66984. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66985. var engine = scene.getEngine();
  66986. var index;
  66987. if (depthOnlySubMeshes.length) {
  66988. engine.setColorWrite(false);
  66989. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66990. renderSubMesh(depthOnlySubMeshes.data[index]);
  66991. }
  66992. engine.setColorWrite(true);
  66993. }
  66994. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66995. renderSubMesh(opaqueSubMeshes.data[index]);
  66996. }
  66997. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66998. renderSubMesh(alphaTestSubMeshes.data[index]);
  66999. }
  67000. if (transparentSubMeshes.length) {
  67001. // Sort sub meshes
  67002. for (index = 0; index < transparentSubMeshes.length; index++) {
  67003. var submesh = transparentSubMeshes.data[index];
  67004. var boundingInfo = submesh.getBoundingInfo();
  67005. if (boundingInfo && scene.activeCamera) {
  67006. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  67007. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  67008. }
  67009. }
  67010. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  67011. sortedArray.sort(function (a, b) {
  67012. // Alpha index first
  67013. if (a._alphaIndex > b._alphaIndex) {
  67014. return 1;
  67015. }
  67016. if (a._alphaIndex < b._alphaIndex) {
  67017. return -1;
  67018. }
  67019. // Then distance to camera
  67020. if (a._distanceToCamera < b._distanceToCamera) {
  67021. return 1;
  67022. }
  67023. if (a._distanceToCamera > b._distanceToCamera) {
  67024. return -1;
  67025. }
  67026. return 0;
  67027. });
  67028. // Render sub meshes
  67029. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  67030. for (index = 0; index < sortedArray.length; index++) {
  67031. renderSubMesh(sortedArray[index]);
  67032. }
  67033. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67034. }
  67035. };
  67036. };
  67037. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  67038. var transform = scene.getTransformMatrix();
  67039. var meshPosition;
  67040. if (this.useCustomMeshPosition) {
  67041. meshPosition = this.customMeshPosition;
  67042. }
  67043. else if (this.attachedNode) {
  67044. meshPosition = this.attachedNode.position;
  67045. }
  67046. else {
  67047. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  67048. }
  67049. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  67050. this._screenCoordinates.x = pos.x / this._viewPort.width;
  67051. this._screenCoordinates.y = pos.y / this._viewPort.height;
  67052. if (this.invert)
  67053. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  67054. };
  67055. // Static methods
  67056. /**
  67057. * Creates a default mesh for the Volumeric Light Scattering post-process
  67058. * @param {string} The mesh name
  67059. * @param {BABYLON.Scene} The scene where to create the mesh
  67060. * @return {BABYLON.Mesh} the default mesh
  67061. */
  67062. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  67063. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  67064. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  67065. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  67066. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  67067. mesh.material = material;
  67068. return mesh;
  67069. };
  67070. __decorate([
  67071. BABYLON.serializeAsVector3()
  67072. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  67073. __decorate([
  67074. BABYLON.serialize()
  67075. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  67076. __decorate([
  67077. BABYLON.serialize()
  67078. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  67079. __decorate([
  67080. BABYLON.serializeAsMeshReference()
  67081. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  67082. __decorate([
  67083. BABYLON.serialize()
  67084. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  67085. __decorate([
  67086. BABYLON.serialize()
  67087. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  67088. __decorate([
  67089. BABYLON.serialize()
  67090. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  67091. __decorate([
  67092. BABYLON.serialize()
  67093. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  67094. __decorate([
  67095. BABYLON.serialize()
  67096. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  67097. return VolumetricLightScatteringPostProcess;
  67098. }(BABYLON.PostProcess));
  67099. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  67100. })(BABYLON || (BABYLON = {}));
  67101. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  67102. //
  67103. // This post-process allows the modification of rendered colors by using
  67104. // a 'look-up table' (LUT). This effect is also called Color Grading.
  67105. //
  67106. // The object needs to be provided an url to a texture containing the color
  67107. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  67108. // Use an image editing software to tweak the LUT to match your needs.
  67109. //
  67110. // For an example of a color LUT, see here:
  67111. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  67112. // For explanations on color grading, see here:
  67113. // http://udn.epicgames.com/Three/ColorGrading.html
  67114. //
  67115. var BABYLON;
  67116. (function (BABYLON) {
  67117. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  67118. __extends(ColorCorrectionPostProcess, _super);
  67119. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  67120. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  67121. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67122. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  67123. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67124. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67125. _this.onApply = function (effect) {
  67126. effect.setTexture("colorTable", _this._colorTableTexture);
  67127. };
  67128. return _this;
  67129. }
  67130. return ColorCorrectionPostProcess;
  67131. }(BABYLON.PostProcess));
  67132. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  67133. })(BABYLON || (BABYLON = {}));
  67134. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  67135. var BABYLON;
  67136. (function (BABYLON) {
  67137. var TonemappingOperator;
  67138. (function (TonemappingOperator) {
  67139. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  67140. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  67141. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  67142. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  67143. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  67144. ;
  67145. var TonemapPostProcess = /** @class */ (function (_super) {
  67146. __extends(TonemapPostProcess, _super);
  67147. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  67148. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67149. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67150. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  67151. _this._operator = _operator;
  67152. _this.exposureAdjustment = exposureAdjustment;
  67153. var defines = "#define ";
  67154. if (_this._operator === TonemappingOperator.Hable)
  67155. defines += "HABLE_TONEMAPPING";
  67156. else if (_this._operator === TonemappingOperator.Reinhard)
  67157. defines += "REINHARD_TONEMAPPING";
  67158. else if (_this._operator === TonemappingOperator.HejiDawson)
  67159. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  67160. else if (_this._operator === TonemappingOperator.Photographic)
  67161. defines += "PHOTOGRAPHIC_TONEMAPPING";
  67162. //sadly a second call to create the effect.
  67163. _this.updateEffect(defines);
  67164. _this.onApply = function (effect) {
  67165. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  67166. };
  67167. return _this;
  67168. }
  67169. return TonemapPostProcess;
  67170. }(BABYLON.PostProcess));
  67171. BABYLON.TonemapPostProcess = TonemapPostProcess;
  67172. })(BABYLON || (BABYLON = {}));
  67173. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  67174. var BABYLON;
  67175. (function (BABYLON) {
  67176. var DisplayPassPostProcess = /** @class */ (function (_super) {
  67177. __extends(DisplayPassPostProcess, _super);
  67178. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  67179. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  67180. }
  67181. return DisplayPassPostProcess;
  67182. }(BABYLON.PostProcess));
  67183. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  67184. })(BABYLON || (BABYLON = {}));
  67185. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  67186. var BABYLON;
  67187. (function (BABYLON) {
  67188. var HighlightsPostProcess = /** @class */ (function (_super) {
  67189. __extends(HighlightsPostProcess, _super);
  67190. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  67191. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67192. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  67193. }
  67194. return HighlightsPostProcess;
  67195. }(BABYLON.PostProcess));
  67196. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  67197. })(BABYLON || (BABYLON = {}));
  67198. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  67199. var BABYLON;
  67200. (function (BABYLON) {
  67201. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  67202. __extends(ImageProcessingPostProcess, _super);
  67203. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  67204. if (camera === void 0) { camera = null; }
  67205. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67206. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  67207. _this._fromLinearSpace = true;
  67208. /**
  67209. * Defines cache preventing GC.
  67210. */
  67211. _this._defines = {
  67212. IMAGEPROCESSING: false,
  67213. VIGNETTE: false,
  67214. VIGNETTEBLENDMODEMULTIPLY: false,
  67215. VIGNETTEBLENDMODEOPAQUE: false,
  67216. TONEMAPPING: false,
  67217. CONTRAST: false,
  67218. COLORCURVES: false,
  67219. COLORGRADING: false,
  67220. COLORGRADING3D: false,
  67221. FROMLINEARSPACE: false,
  67222. SAMPLER3DGREENDEPTH: false,
  67223. SAMPLER3DBGRMAP: false,
  67224. IMAGEPROCESSINGPOSTPROCESS: false,
  67225. EXPOSURE: false,
  67226. };
  67227. // Setup the configuration as forced by the constructor. This would then not force the
  67228. // scene materials output in linear space and let untouched the default forward pass.
  67229. if (imageProcessingConfiguration) {
  67230. imageProcessingConfiguration.applyByPostProcess = true;
  67231. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  67232. // This will cause the shader to be compiled
  67233. _this.fromLinearSpace = false;
  67234. }
  67235. else {
  67236. _this._attachImageProcessingConfiguration(null, true);
  67237. _this.imageProcessingConfiguration.applyByPostProcess = true;
  67238. }
  67239. _this.onApply = function (effect) {
  67240. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  67241. };
  67242. return _this;
  67243. }
  67244. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  67245. /**
  67246. * Gets the image processing configuration used either in this material.
  67247. */
  67248. get: function () {
  67249. return this._imageProcessingConfiguration;
  67250. },
  67251. /**
  67252. * Sets the Default image processing configuration used either in the this material.
  67253. *
  67254. * If sets to null, the scene one is in use.
  67255. */
  67256. set: function (value) {
  67257. this._attachImageProcessingConfiguration(value);
  67258. },
  67259. enumerable: true,
  67260. configurable: true
  67261. });
  67262. /**
  67263. * Attaches a new image processing configuration to the PBR Material.
  67264. * @param configuration
  67265. */
  67266. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  67267. var _this = this;
  67268. if (doNotBuild === void 0) { doNotBuild = false; }
  67269. if (configuration === this._imageProcessingConfiguration) {
  67270. return;
  67271. }
  67272. // Detaches observer.
  67273. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  67274. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  67275. }
  67276. // Pick the scene configuration if needed.
  67277. if (!configuration) {
  67278. var scene = null;
  67279. var engine = this.getEngine();
  67280. var camera = this.getCamera();
  67281. if (camera) {
  67282. scene = camera.getScene();
  67283. }
  67284. else if (engine && engine.scenes) {
  67285. var scenes = engine.scenes;
  67286. scene = scenes[scenes.length - 1];
  67287. }
  67288. else {
  67289. scene = BABYLON.Engine.LastCreatedScene;
  67290. }
  67291. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  67292. }
  67293. else {
  67294. this._imageProcessingConfiguration = configuration;
  67295. }
  67296. // Attaches observer.
  67297. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  67298. _this._updateParameters();
  67299. });
  67300. // Ensure the effect will be rebuilt.
  67301. if (!doNotBuild) {
  67302. this._updateParameters();
  67303. }
  67304. };
  67305. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  67306. /**
  67307. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  67308. */
  67309. get: function () {
  67310. return this.imageProcessingConfiguration.colorCurves;
  67311. },
  67312. /**
  67313. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  67314. */
  67315. set: function (value) {
  67316. this.imageProcessingConfiguration.colorCurves = value;
  67317. },
  67318. enumerable: true,
  67319. configurable: true
  67320. });
  67321. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  67322. /**
  67323. * Gets wether the color curves effect is enabled.
  67324. */
  67325. get: function () {
  67326. return this.imageProcessingConfiguration.colorCurvesEnabled;
  67327. },
  67328. /**
  67329. * Sets wether the color curves effect is enabled.
  67330. */
  67331. set: function (value) {
  67332. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  67333. },
  67334. enumerable: true,
  67335. configurable: true
  67336. });
  67337. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  67338. /**
  67339. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  67340. */
  67341. get: function () {
  67342. return this.imageProcessingConfiguration.colorGradingTexture;
  67343. },
  67344. /**
  67345. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  67346. */
  67347. set: function (value) {
  67348. this.imageProcessingConfiguration.colorGradingTexture = value;
  67349. },
  67350. enumerable: true,
  67351. configurable: true
  67352. });
  67353. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  67354. /**
  67355. * Gets wether the color grading effect is enabled.
  67356. */
  67357. get: function () {
  67358. return this.imageProcessingConfiguration.colorGradingEnabled;
  67359. },
  67360. /**
  67361. * Gets wether the color grading effect is enabled.
  67362. */
  67363. set: function (value) {
  67364. this.imageProcessingConfiguration.colorGradingEnabled = value;
  67365. },
  67366. enumerable: true,
  67367. configurable: true
  67368. });
  67369. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  67370. /**
  67371. * Gets exposure used in the effect.
  67372. */
  67373. get: function () {
  67374. return this.imageProcessingConfiguration.exposure;
  67375. },
  67376. /**
  67377. * Sets exposure used in the effect.
  67378. */
  67379. set: function (value) {
  67380. this.imageProcessingConfiguration.exposure = value;
  67381. },
  67382. enumerable: true,
  67383. configurable: true
  67384. });
  67385. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  67386. /**
  67387. * Gets wether tonemapping is enabled or not.
  67388. */
  67389. get: function () {
  67390. return this._imageProcessingConfiguration.toneMappingEnabled;
  67391. },
  67392. /**
  67393. * Sets wether tonemapping is enabled or not
  67394. */
  67395. set: function (value) {
  67396. this._imageProcessingConfiguration.toneMappingEnabled = value;
  67397. },
  67398. enumerable: true,
  67399. configurable: true
  67400. });
  67401. ;
  67402. ;
  67403. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  67404. /**
  67405. * Gets contrast used in the effect.
  67406. */
  67407. get: function () {
  67408. return this.imageProcessingConfiguration.contrast;
  67409. },
  67410. /**
  67411. * Sets contrast used in the effect.
  67412. */
  67413. set: function (value) {
  67414. this.imageProcessingConfiguration.contrast = value;
  67415. },
  67416. enumerable: true,
  67417. configurable: true
  67418. });
  67419. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  67420. /**
  67421. * Gets Vignette stretch size.
  67422. */
  67423. get: function () {
  67424. return this.imageProcessingConfiguration.vignetteStretch;
  67425. },
  67426. /**
  67427. * Sets Vignette stretch size.
  67428. */
  67429. set: function (value) {
  67430. this.imageProcessingConfiguration.vignetteStretch = value;
  67431. },
  67432. enumerable: true,
  67433. configurable: true
  67434. });
  67435. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  67436. /**
  67437. * Gets Vignette centre X Offset.
  67438. */
  67439. get: function () {
  67440. return this.imageProcessingConfiguration.vignetteCentreX;
  67441. },
  67442. /**
  67443. * Sets Vignette centre X Offset.
  67444. */
  67445. set: function (value) {
  67446. this.imageProcessingConfiguration.vignetteCentreX = value;
  67447. },
  67448. enumerable: true,
  67449. configurable: true
  67450. });
  67451. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  67452. /**
  67453. * Gets Vignette centre Y Offset.
  67454. */
  67455. get: function () {
  67456. return this.imageProcessingConfiguration.vignetteCentreY;
  67457. },
  67458. /**
  67459. * Sets Vignette centre Y Offset.
  67460. */
  67461. set: function (value) {
  67462. this.imageProcessingConfiguration.vignetteCentreY = value;
  67463. },
  67464. enumerable: true,
  67465. configurable: true
  67466. });
  67467. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  67468. /**
  67469. * Gets Vignette weight or intensity of the vignette effect.
  67470. */
  67471. get: function () {
  67472. return this.imageProcessingConfiguration.vignetteWeight;
  67473. },
  67474. /**
  67475. * Sets Vignette weight or intensity of the vignette effect.
  67476. */
  67477. set: function (value) {
  67478. this.imageProcessingConfiguration.vignetteWeight = value;
  67479. },
  67480. enumerable: true,
  67481. configurable: true
  67482. });
  67483. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  67484. /**
  67485. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  67486. * if vignetteEnabled is set to true.
  67487. */
  67488. get: function () {
  67489. return this.imageProcessingConfiguration.vignetteColor;
  67490. },
  67491. /**
  67492. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  67493. * if vignetteEnabled is set to true.
  67494. */
  67495. set: function (value) {
  67496. this.imageProcessingConfiguration.vignetteColor = value;
  67497. },
  67498. enumerable: true,
  67499. configurable: true
  67500. });
  67501. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  67502. /**
  67503. * Gets Camera field of view used by the Vignette effect.
  67504. */
  67505. get: function () {
  67506. return this.imageProcessingConfiguration.vignetteCameraFov;
  67507. },
  67508. /**
  67509. * Sets Camera field of view used by the Vignette effect.
  67510. */
  67511. set: function (value) {
  67512. this.imageProcessingConfiguration.vignetteCameraFov = value;
  67513. },
  67514. enumerable: true,
  67515. configurable: true
  67516. });
  67517. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  67518. /**
  67519. * Gets the vignette blend mode allowing different kind of effect.
  67520. */
  67521. get: function () {
  67522. return this.imageProcessingConfiguration.vignetteBlendMode;
  67523. },
  67524. /**
  67525. * Sets the vignette blend mode allowing different kind of effect.
  67526. */
  67527. set: function (value) {
  67528. this.imageProcessingConfiguration.vignetteBlendMode = value;
  67529. },
  67530. enumerable: true,
  67531. configurable: true
  67532. });
  67533. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  67534. /**
  67535. * Gets wether the vignette effect is enabled.
  67536. */
  67537. get: function () {
  67538. return this.imageProcessingConfiguration.vignetteEnabled;
  67539. },
  67540. /**
  67541. * Sets wether the vignette effect is enabled.
  67542. */
  67543. set: function (value) {
  67544. this.imageProcessingConfiguration.vignetteEnabled = value;
  67545. },
  67546. enumerable: true,
  67547. configurable: true
  67548. });
  67549. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  67550. /**
  67551. * Gets wether the input of the processing is in Gamma or Linear Space.
  67552. */
  67553. get: function () {
  67554. return this._fromLinearSpace;
  67555. },
  67556. /**
  67557. * Sets wether the input of the processing is in Gamma or Linear Space.
  67558. */
  67559. set: function (value) {
  67560. if (this._fromLinearSpace === value) {
  67561. return;
  67562. }
  67563. this._fromLinearSpace = value;
  67564. this._updateParameters();
  67565. },
  67566. enumerable: true,
  67567. configurable: true
  67568. });
  67569. ImageProcessingPostProcess.prototype.getClassName = function () {
  67570. return "ImageProcessingPostProcess";
  67571. };
  67572. ImageProcessingPostProcess.prototype._updateParameters = function () {
  67573. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  67574. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  67575. var defines = "";
  67576. for (var define in this._defines) {
  67577. if (this._defines[define]) {
  67578. defines += "#define " + define + ";\r\n";
  67579. }
  67580. }
  67581. var samplers = ["textureSampler"];
  67582. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  67583. var uniforms = ["scale"];
  67584. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  67585. this.updateEffect(defines, uniforms, samplers);
  67586. };
  67587. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  67588. _super.prototype.dispose.call(this, camera);
  67589. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  67590. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  67591. }
  67592. this.imageProcessingConfiguration.applyByPostProcess = false;
  67593. };
  67594. __decorate([
  67595. BABYLON.serialize()
  67596. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  67597. return ImageProcessingPostProcess;
  67598. }(BABYLON.PostProcess));
  67599. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  67600. })(BABYLON || (BABYLON = {}));
  67601. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  67602. var BABYLON;
  67603. (function (BABYLON) {
  67604. /**
  67605. * The Blur Post Process which blurs an image based on a kernel and direction.
  67606. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  67607. */
  67608. var BlurPostProcess = /** @class */ (function (_super) {
  67609. __extends(BlurPostProcess, _super);
  67610. /**
  67611. * Creates a new instance of @see BlurPostProcess
  67612. * @param name The name of the effect.
  67613. * @param direction The direction in which to blur the image.
  67614. * @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.
  67615. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  67616. * @param camera The camera to apply the render pass to.
  67617. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67618. * @param engine The engine which the post process will be applied. (default: current engine)
  67619. * @param reusable If the post process can be reused on the same frame. (default: false)
  67620. * @param textureType Type of textures used when performing the post process. (default: 0)
  67621. */
  67622. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  67623. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67624. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67625. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  67626. _this.direction = direction;
  67627. _this._packedFloat = false;
  67628. _this._staticDefines = "";
  67629. _this.onApplyObservable.add(function (effect) {
  67630. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  67631. });
  67632. _this.kernel = kernel;
  67633. return _this;
  67634. }
  67635. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  67636. /**
  67637. * Gets the length in pixels of the blur sample region
  67638. */
  67639. get: function () {
  67640. return this._idealKernel;
  67641. },
  67642. /**
  67643. * Sets the length in pixels of the blur sample region
  67644. */
  67645. set: function (v) {
  67646. if (this._idealKernel === v) {
  67647. return;
  67648. }
  67649. v = Math.max(v, 1);
  67650. this._idealKernel = v;
  67651. this._kernel = this._nearestBestKernel(v);
  67652. this._updateParameters();
  67653. },
  67654. enumerable: true,
  67655. configurable: true
  67656. });
  67657. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  67658. /**
  67659. * Gets wether or not the blur is unpacking/repacking floats
  67660. */
  67661. get: function () {
  67662. return this._packedFloat;
  67663. },
  67664. /**
  67665. * Sets wether or not the blur needs to unpack/repack floats
  67666. */
  67667. set: function (v) {
  67668. if (this._packedFloat === v) {
  67669. return;
  67670. }
  67671. this._packedFloat = v;
  67672. this._updateParameters();
  67673. },
  67674. enumerable: true,
  67675. configurable: true
  67676. });
  67677. BlurPostProcess.prototype._updateParameters = function () {
  67678. // Generate sampling offsets and weights
  67679. var N = this._kernel;
  67680. var centerIndex = (N - 1) / 2;
  67681. // Generate Gaussian sampling weights over kernel
  67682. var offsets = [];
  67683. var weights = [];
  67684. var totalWeight = 0;
  67685. for (var i = 0; i < N; i++) {
  67686. var u = i / (N - 1);
  67687. var w = this._gaussianWeight(u * 2.0 - 1);
  67688. offsets[i] = (i - centerIndex);
  67689. weights[i] = w;
  67690. totalWeight += w;
  67691. }
  67692. // Normalize weights
  67693. for (var i = 0; i < weights.length; i++) {
  67694. weights[i] /= totalWeight;
  67695. }
  67696. // Optimize: combine samples to take advantage of hardware linear sampling
  67697. // Walk from left to center, combining pairs (symmetrically)
  67698. var linearSamplingWeights = [];
  67699. var linearSamplingOffsets = [];
  67700. var linearSamplingMap = [];
  67701. for (var i = 0; i <= centerIndex; i += 2) {
  67702. var j = Math.min(i + 1, Math.floor(centerIndex));
  67703. var singleCenterSample = i === j;
  67704. if (singleCenterSample) {
  67705. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  67706. }
  67707. else {
  67708. var sharedCell = j === centerIndex;
  67709. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  67710. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  67711. if (offsetLinear === 0) {
  67712. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  67713. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  67714. }
  67715. else {
  67716. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  67717. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  67718. }
  67719. }
  67720. }
  67721. for (var i = 0; i < linearSamplingMap.length; i++) {
  67722. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  67723. linearSamplingWeights[i] = linearSamplingMap[i].w;
  67724. }
  67725. // Replace with optimized
  67726. offsets = linearSamplingOffsets;
  67727. weights = linearSamplingWeights;
  67728. // Generate shaders
  67729. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  67730. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  67731. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  67732. var defines = "";
  67733. defines += this._staticDefines;
  67734. for (var i = 0; i < varyingCount; i++) {
  67735. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  67736. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  67737. }
  67738. var depCount = 0;
  67739. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  67740. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  67741. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  67742. depCount++;
  67743. }
  67744. if (this.packedFloat) {
  67745. defines += "#define PACKEDFLOAT 1";
  67746. }
  67747. this.updateEffect(defines, null, null, {
  67748. varyingCount: varyingCount,
  67749. depCount: depCount
  67750. });
  67751. };
  67752. /**
  67753. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  67754. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  67755. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  67756. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  67757. * The gaps between physical kernels are compensated for in the weighting of the samples
  67758. * @param idealKernel Ideal blur kernel.
  67759. * @return Nearest best kernel.
  67760. */
  67761. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  67762. var v = Math.round(idealKernel);
  67763. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  67764. var k = _a[_i];
  67765. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  67766. return Math.max(k, 3);
  67767. }
  67768. }
  67769. return Math.max(v, 3);
  67770. };
  67771. /**
  67772. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  67773. * @param x The point on the Gaussian distribution to sample.
  67774. * @return the value of the Gaussian function at x.
  67775. */
  67776. BlurPostProcess.prototype._gaussianWeight = function (x) {
  67777. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  67778. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  67779. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  67780. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  67781. // truncated at around 1.3% of peak strength.
  67782. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  67783. var sigma = (1 / 3);
  67784. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  67785. var exponent = -((x * x) / (2.0 * sigma * sigma));
  67786. var weight = (1.0 / denominator) * Math.exp(exponent);
  67787. return weight;
  67788. };
  67789. /**
  67790. * Generates a string that can be used as a floating point number in GLSL.
  67791. * @param x Value to print.
  67792. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  67793. * @return GLSL float string.
  67794. */
  67795. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  67796. if (decimalFigures === void 0) { decimalFigures = 8; }
  67797. return x.toFixed(decimalFigures).replace(/0+$/, '');
  67798. };
  67799. return BlurPostProcess;
  67800. }(BABYLON.PostProcess));
  67801. BABYLON.BlurPostProcess = BlurPostProcess;
  67802. })(BABYLON || (BABYLON = {}));
  67803. //# sourceMappingURL=babylon.blurPostProcess.js.map
  67804. var BABYLON;
  67805. (function (BABYLON) {
  67806. var Bone = /** @class */ (function (_super) {
  67807. __extends(Bone, _super);
  67808. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  67809. if (parentBone === void 0) { parentBone = null; }
  67810. if (localMatrix === void 0) { localMatrix = null; }
  67811. if (restPose === void 0) { restPose = null; }
  67812. if (baseMatrix === void 0) { baseMatrix = null; }
  67813. if (index === void 0) { index = null; }
  67814. var _this = _super.call(this, name, skeleton.getScene()) || this;
  67815. _this.name = name;
  67816. _this.children = new Array();
  67817. _this.animations = new Array();
  67818. // Set this value to map this bone to a different index in the transform matrices.
  67819. // Set this value to -1 to exclude the bone from the transform matrices.
  67820. _this._index = null;
  67821. _this._worldTransform = new BABYLON.Matrix();
  67822. _this._absoluteTransform = new BABYLON.Matrix();
  67823. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  67824. _this._scaleMatrix = BABYLON.Matrix.Identity();
  67825. _this._scaleVector = BABYLON.Vector3.One();
  67826. _this._negateScaleChildren = BABYLON.Vector3.One();
  67827. _this._scalingDeterminant = 1;
  67828. _this._skeleton = skeleton;
  67829. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  67830. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  67831. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  67832. _this._index = index;
  67833. skeleton.bones.push(_this);
  67834. _this.setParent(parentBone, false);
  67835. _this._updateDifferenceMatrix();
  67836. return _this;
  67837. }
  67838. Object.defineProperty(Bone.prototype, "_matrix", {
  67839. get: function () {
  67840. return this._localMatrix;
  67841. },
  67842. set: function (val) {
  67843. if (this._localMatrix) {
  67844. this._localMatrix.copyFrom(val);
  67845. }
  67846. else {
  67847. this._localMatrix = val;
  67848. }
  67849. },
  67850. enumerable: true,
  67851. configurable: true
  67852. });
  67853. // Members
  67854. Bone.prototype.getSkeleton = function () {
  67855. return this._skeleton;
  67856. };
  67857. Bone.prototype.getParent = function () {
  67858. return this._parent;
  67859. };
  67860. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  67861. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  67862. if (this._parent === parent) {
  67863. return;
  67864. }
  67865. if (this._parent) {
  67866. var index = this._parent.children.indexOf(this);
  67867. if (index !== -1) {
  67868. this._parent.children.splice(index, 1);
  67869. }
  67870. }
  67871. this._parent = parent;
  67872. if (this._parent) {
  67873. this._parent.children.push(this);
  67874. }
  67875. if (updateDifferenceMatrix) {
  67876. this._updateDifferenceMatrix();
  67877. }
  67878. };
  67879. Bone.prototype.getLocalMatrix = function () {
  67880. return this._localMatrix;
  67881. };
  67882. Bone.prototype.getBaseMatrix = function () {
  67883. return this._baseMatrix;
  67884. };
  67885. Bone.prototype.getRestPose = function () {
  67886. return this._restPose;
  67887. };
  67888. Bone.prototype.returnToRest = function () {
  67889. this.updateMatrix(this._restPose.clone());
  67890. };
  67891. Bone.prototype.getWorldMatrix = function () {
  67892. return this._worldTransform;
  67893. };
  67894. Bone.prototype.getInvertedAbsoluteTransform = function () {
  67895. return this._invertedAbsoluteTransform;
  67896. };
  67897. Bone.prototype.getAbsoluteTransform = function () {
  67898. return this._absoluteTransform;
  67899. };
  67900. Object.defineProperty(Bone.prototype, "position", {
  67901. // Properties (matches AbstractMesh properties)
  67902. get: function () {
  67903. return this.getPosition();
  67904. },
  67905. set: function (newPosition) {
  67906. this.setPosition(newPosition);
  67907. },
  67908. enumerable: true,
  67909. configurable: true
  67910. });
  67911. Object.defineProperty(Bone.prototype, "rotation", {
  67912. get: function () {
  67913. return this.getRotation();
  67914. },
  67915. set: function (newRotation) {
  67916. this.setRotation(newRotation);
  67917. },
  67918. enumerable: true,
  67919. configurable: true
  67920. });
  67921. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  67922. get: function () {
  67923. return this.getRotationQuaternion();
  67924. },
  67925. set: function (newRotation) {
  67926. this.setRotationQuaternion(newRotation);
  67927. },
  67928. enumerable: true,
  67929. configurable: true
  67930. });
  67931. Object.defineProperty(Bone.prototype, "scaling", {
  67932. get: function () {
  67933. return this.getScale();
  67934. },
  67935. set: function (newScaling) {
  67936. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  67937. },
  67938. enumerable: true,
  67939. configurable: true
  67940. });
  67941. // Methods
  67942. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  67943. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  67944. this._baseMatrix = matrix.clone();
  67945. this._localMatrix = matrix.clone();
  67946. this._skeleton._markAsDirty();
  67947. if (updateDifferenceMatrix) {
  67948. this._updateDifferenceMatrix();
  67949. }
  67950. };
  67951. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  67952. if (!rootMatrix) {
  67953. rootMatrix = this._baseMatrix;
  67954. }
  67955. if (this._parent) {
  67956. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  67957. }
  67958. else {
  67959. this._absoluteTransform.copyFrom(rootMatrix);
  67960. }
  67961. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  67962. for (var index = 0; index < this.children.length; index++) {
  67963. this.children[index]._updateDifferenceMatrix();
  67964. }
  67965. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  67966. };
  67967. Bone.prototype.markAsDirty = function () {
  67968. this._currentRenderId++;
  67969. this._skeleton._markAsDirty();
  67970. };
  67971. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  67972. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  67973. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  67974. // all animation may be coming from a library skeleton, so may need to create animation
  67975. if (this.animations.length === 0) {
  67976. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  67977. this.animations[0].setKeys([]);
  67978. }
  67979. // get animation info / verify there is such a range from the source bone
  67980. var sourceRange = source.animations[0].getRange(rangeName);
  67981. if (!sourceRange) {
  67982. return false;
  67983. }
  67984. var from = sourceRange.from;
  67985. var to = sourceRange.to;
  67986. var sourceKeys = source.animations[0].getKeys();
  67987. // rescaling prep
  67988. var sourceBoneLength = source.length;
  67989. var sourceParent = source.getParent();
  67990. var parent = this.getParent();
  67991. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  67992. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  67993. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  67994. var destKeys = this.animations[0].getKeys();
  67995. // loop vars declaration
  67996. var orig;
  67997. var origTranslation;
  67998. var mat;
  67999. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  68000. orig = sourceKeys[key];
  68001. if (orig.frame >= from && orig.frame <= to) {
  68002. if (rescaleAsRequired) {
  68003. mat = orig.value.clone();
  68004. // scale based on parent ratio, when bone has parent
  68005. if (parentScalingReqd) {
  68006. origTranslation = mat.getTranslation();
  68007. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  68008. // scale based on skeleton dimension ratio when root bone, and value is passed
  68009. }
  68010. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  68011. origTranslation = mat.getTranslation();
  68012. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  68013. // use original when root bone, and no data for skelDimensionsRatio
  68014. }
  68015. else {
  68016. mat = orig.value;
  68017. }
  68018. }
  68019. else {
  68020. mat = orig.value;
  68021. }
  68022. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  68023. }
  68024. }
  68025. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  68026. return true;
  68027. };
  68028. /**
  68029. * Translate the bone in local or world space.
  68030. * @param vec The amount to translate the bone.
  68031. * @param space The space that the translation is in.
  68032. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68033. */
  68034. Bone.prototype.translate = function (vec, space, mesh) {
  68035. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68036. var lm = this.getLocalMatrix();
  68037. if (space == BABYLON.Space.LOCAL) {
  68038. lm.m[12] += vec.x;
  68039. lm.m[13] += vec.y;
  68040. lm.m[14] += vec.z;
  68041. }
  68042. else {
  68043. var wm = null;
  68044. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68045. if (mesh) {
  68046. wm = mesh.getWorldMatrix();
  68047. }
  68048. this._skeleton.computeAbsoluteTransforms();
  68049. var tmat = Bone._tmpMats[0];
  68050. var tvec = Bone._tmpVecs[0];
  68051. if (this._parent) {
  68052. if (mesh && wm) {
  68053. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68054. tmat.multiplyToRef(wm, tmat);
  68055. }
  68056. else {
  68057. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68058. }
  68059. }
  68060. tmat.m[12] = 0;
  68061. tmat.m[13] = 0;
  68062. tmat.m[14] = 0;
  68063. tmat.invert();
  68064. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  68065. lm.m[12] += tvec.x;
  68066. lm.m[13] += tvec.y;
  68067. lm.m[14] += tvec.z;
  68068. }
  68069. this.markAsDirty();
  68070. };
  68071. /**
  68072. * Set the postion of the bone in local or world space.
  68073. * @param position The position to set the bone.
  68074. * @param space The space that the position is in.
  68075. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68076. */
  68077. Bone.prototype.setPosition = function (position, space, mesh) {
  68078. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68079. var lm = this.getLocalMatrix();
  68080. if (space == BABYLON.Space.LOCAL) {
  68081. lm.m[12] = position.x;
  68082. lm.m[13] = position.y;
  68083. lm.m[14] = position.z;
  68084. }
  68085. else {
  68086. var wm = null;
  68087. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68088. if (mesh) {
  68089. wm = mesh.getWorldMatrix();
  68090. }
  68091. this._skeleton.computeAbsoluteTransforms();
  68092. var tmat = Bone._tmpMats[0];
  68093. var vec = Bone._tmpVecs[0];
  68094. if (this._parent) {
  68095. if (mesh && wm) {
  68096. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68097. tmat.multiplyToRef(wm, tmat);
  68098. }
  68099. else {
  68100. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68101. }
  68102. }
  68103. tmat.invert();
  68104. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  68105. lm.m[12] = vec.x;
  68106. lm.m[13] = vec.y;
  68107. lm.m[14] = vec.z;
  68108. }
  68109. this.markAsDirty();
  68110. };
  68111. /**
  68112. * Set the absolute postion of the bone (world space).
  68113. * @param position The position to set the bone.
  68114. * @param mesh The mesh that this bone is attached to.
  68115. */
  68116. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  68117. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  68118. };
  68119. /**
  68120. * Set the scale of the bone on the x, y and z axes.
  68121. * @param x The scale of the bone on the x axis.
  68122. * @param x The scale of the bone on the y axis.
  68123. * @param z The scale of the bone on the z axis.
  68124. * @param scaleChildren Set this to true if children of the bone should be scaled.
  68125. */
  68126. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  68127. if (scaleChildren === void 0) { scaleChildren = false; }
  68128. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  68129. if (!scaleChildren) {
  68130. this._negateScaleChildren.x = 1 / x;
  68131. this._negateScaleChildren.y = 1 / y;
  68132. this._negateScaleChildren.z = 1 / z;
  68133. }
  68134. this._syncScaleVector();
  68135. }
  68136. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  68137. };
  68138. /**
  68139. * Scale the bone on the x, y and z axes.
  68140. * @param x The amount to scale the bone on the x axis.
  68141. * @param x The amount to scale the bone on the y axis.
  68142. * @param z The amount to scale the bone on the z axis.
  68143. * @param scaleChildren Set this to true if children of the bone should be scaled.
  68144. */
  68145. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  68146. if (scaleChildren === void 0) { scaleChildren = false; }
  68147. var locMat = this.getLocalMatrix();
  68148. var origLocMat = Bone._tmpMats[0];
  68149. origLocMat.copyFrom(locMat);
  68150. var origLocMatInv = Bone._tmpMats[1];
  68151. origLocMatInv.copyFrom(origLocMat);
  68152. origLocMatInv.invert();
  68153. var scaleMat = Bone._tmpMats[2];
  68154. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  68155. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  68156. this._scaleVector.x *= x;
  68157. this._scaleVector.y *= y;
  68158. this._scaleVector.z *= z;
  68159. locMat.multiplyToRef(origLocMatInv, locMat);
  68160. locMat.multiplyToRef(scaleMat, locMat);
  68161. locMat.multiplyToRef(origLocMat, locMat);
  68162. var parent = this.getParent();
  68163. if (parent) {
  68164. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  68165. }
  68166. else {
  68167. this.getAbsoluteTransform().copyFrom(locMat);
  68168. }
  68169. var len = this.children.length;
  68170. scaleMat.invert();
  68171. for (var i = 0; i < len; i++) {
  68172. var child = this.children[i];
  68173. var cm = child.getLocalMatrix();
  68174. cm.multiplyToRef(scaleMat, cm);
  68175. var lm = child.getLocalMatrix();
  68176. lm.m[12] *= x;
  68177. lm.m[13] *= y;
  68178. lm.m[14] *= z;
  68179. }
  68180. this.computeAbsoluteTransforms();
  68181. if (scaleChildren) {
  68182. for (var i = 0; i < len; i++) {
  68183. this.children[i].scale(x, y, z, scaleChildren);
  68184. }
  68185. }
  68186. this.markAsDirty();
  68187. };
  68188. /**
  68189. * Set the yaw, pitch, and roll of the bone in local or world space.
  68190. * @param yaw The rotation of the bone on the y axis.
  68191. * @param pitch The rotation of the bone on the x axis.
  68192. * @param roll The rotation of the bone on the z axis.
  68193. * @param space The space that the axes of rotation are in.
  68194. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68195. */
  68196. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  68197. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68198. var rotMat = Bone._tmpMats[0];
  68199. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  68200. var rotMatInv = Bone._tmpMats[1];
  68201. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68202. rotMatInv.multiplyToRef(rotMat, rotMat);
  68203. this._rotateWithMatrix(rotMat, space, mesh);
  68204. };
  68205. /**
  68206. * Rotate the bone on an axis in local or world space.
  68207. * @param axis The axis to rotate the bone on.
  68208. * @param amount The amount to rotate the bone.
  68209. * @param space The space that the axis is in.
  68210. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68211. */
  68212. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  68213. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68214. var rmat = Bone._tmpMats[0];
  68215. rmat.m[12] = 0;
  68216. rmat.m[13] = 0;
  68217. rmat.m[14] = 0;
  68218. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  68219. this._rotateWithMatrix(rmat, space, mesh);
  68220. };
  68221. /**
  68222. * Set the rotation of the bone to a particular axis angle in local or world space.
  68223. * @param axis The axis to rotate the bone on.
  68224. * @param angle The angle that the bone should be rotated to.
  68225. * @param space The space that the axis is in.
  68226. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68227. */
  68228. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  68229. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68230. var rotMat = Bone._tmpMats[0];
  68231. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  68232. var rotMatInv = Bone._tmpMats[1];
  68233. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68234. rotMatInv.multiplyToRef(rotMat, rotMat);
  68235. this._rotateWithMatrix(rotMat, space, mesh);
  68236. };
  68237. /**
  68238. * Set the euler rotation of the bone in local of world space.
  68239. * @param rotation The euler rotation that the bone should be set to.
  68240. * @param space The space that the rotation is in.
  68241. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68242. */
  68243. Bone.prototype.setRotation = function (rotation, space, mesh) {
  68244. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68245. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  68246. };
  68247. /**
  68248. * Set the quaternion rotation of the bone in local of world space.
  68249. * @param quat The quaternion rotation that the bone should be set to.
  68250. * @param space The space that the rotation is in.
  68251. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68252. */
  68253. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  68254. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68255. var rotMatInv = Bone._tmpMats[0];
  68256. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68257. var rotMat = Bone._tmpMats[1];
  68258. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  68259. rotMatInv.multiplyToRef(rotMat, rotMat);
  68260. this._rotateWithMatrix(rotMat, space, mesh);
  68261. };
  68262. /**
  68263. * Set the rotation matrix of the bone in local of world space.
  68264. * @param rotMat The rotation matrix that the bone should be set to.
  68265. * @param space The space that the rotation is in.
  68266. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68267. */
  68268. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  68269. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68270. var rotMatInv = Bone._tmpMats[0];
  68271. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68272. var rotMat2 = Bone._tmpMats[1];
  68273. rotMat2.copyFrom(rotMat);
  68274. rotMatInv.multiplyToRef(rotMat, rotMat2);
  68275. this._rotateWithMatrix(rotMat2, space, mesh);
  68276. };
  68277. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  68278. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68279. var lmat = this.getLocalMatrix();
  68280. var lx = lmat.m[12];
  68281. var ly = lmat.m[13];
  68282. var lz = lmat.m[14];
  68283. var parent = this.getParent();
  68284. var parentScale = Bone._tmpMats[3];
  68285. var parentScaleInv = Bone._tmpMats[4];
  68286. if (parent) {
  68287. if (space == BABYLON.Space.WORLD) {
  68288. if (mesh) {
  68289. parentScale.copyFrom(mesh.getWorldMatrix());
  68290. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  68291. }
  68292. else {
  68293. parentScale.copyFrom(parent.getAbsoluteTransform());
  68294. }
  68295. }
  68296. else {
  68297. parentScale = parent._scaleMatrix;
  68298. }
  68299. parentScaleInv.copyFrom(parentScale);
  68300. parentScaleInv.invert();
  68301. lmat.multiplyToRef(parentScale, lmat);
  68302. lmat.multiplyToRef(rmat, lmat);
  68303. lmat.multiplyToRef(parentScaleInv, lmat);
  68304. }
  68305. else {
  68306. if (space == BABYLON.Space.WORLD && mesh) {
  68307. parentScale.copyFrom(mesh.getWorldMatrix());
  68308. parentScaleInv.copyFrom(parentScale);
  68309. parentScaleInv.invert();
  68310. lmat.multiplyToRef(parentScale, lmat);
  68311. lmat.multiplyToRef(rmat, lmat);
  68312. lmat.multiplyToRef(parentScaleInv, lmat);
  68313. }
  68314. else {
  68315. lmat.multiplyToRef(rmat, lmat);
  68316. }
  68317. }
  68318. lmat.m[12] = lx;
  68319. lmat.m[13] = ly;
  68320. lmat.m[14] = lz;
  68321. this.computeAbsoluteTransforms();
  68322. this.markAsDirty();
  68323. };
  68324. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  68325. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68326. if (space == BABYLON.Space.WORLD) {
  68327. var scaleMatrix = Bone._tmpMats[2];
  68328. scaleMatrix.copyFrom(this._scaleMatrix);
  68329. rotMatInv.copyFrom(this.getAbsoluteTransform());
  68330. if (mesh) {
  68331. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  68332. var meshScale = Bone._tmpMats[3];
  68333. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  68334. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  68335. }
  68336. rotMatInv.invert();
  68337. scaleMatrix.m[0] *= this._scalingDeterminant;
  68338. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  68339. }
  68340. else {
  68341. rotMatInv.copyFrom(this.getLocalMatrix());
  68342. rotMatInv.invert();
  68343. var scaleMatrix = Bone._tmpMats[2];
  68344. scaleMatrix.copyFrom(this._scaleMatrix);
  68345. if (this._parent) {
  68346. var pscaleMatrix = Bone._tmpMats[3];
  68347. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  68348. pscaleMatrix.invert();
  68349. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  68350. }
  68351. else {
  68352. scaleMatrix.m[0] *= this._scalingDeterminant;
  68353. }
  68354. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  68355. }
  68356. };
  68357. /**
  68358. * Get the scale of the bone
  68359. * @returns the scale of the bone
  68360. */
  68361. Bone.prototype.getScale = function () {
  68362. return this._scaleVector.clone();
  68363. };
  68364. /**
  68365. * Copy the scale of the bone to a vector3.
  68366. * @param result The vector3 to copy the scale to
  68367. */
  68368. Bone.prototype.getScaleToRef = function (result) {
  68369. result.copyFrom(this._scaleVector);
  68370. };
  68371. /**
  68372. * Get the position of the bone in local or world space.
  68373. * @param space The space that the returned position is in.
  68374. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68375. * @returns The position of the bone
  68376. */
  68377. Bone.prototype.getPosition = function (space, mesh) {
  68378. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68379. if (mesh === void 0) { mesh = null; }
  68380. var pos = BABYLON.Vector3.Zero();
  68381. this.getPositionToRef(space, mesh, pos);
  68382. return pos;
  68383. };
  68384. /**
  68385. * Copy the position of the bone to a vector3 in local or world space.
  68386. * @param space The space that the returned position is in.
  68387. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68388. * @param result The vector3 to copy the position to.
  68389. */
  68390. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  68391. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68392. if (space == BABYLON.Space.LOCAL) {
  68393. var lm = this.getLocalMatrix();
  68394. result.x = lm.m[12];
  68395. result.y = lm.m[13];
  68396. result.z = lm.m[14];
  68397. }
  68398. else {
  68399. var wm = null;
  68400. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68401. if (mesh) {
  68402. wm = mesh.getWorldMatrix();
  68403. }
  68404. this._skeleton.computeAbsoluteTransforms();
  68405. var tmat = Bone._tmpMats[0];
  68406. if (mesh && wm) {
  68407. tmat.copyFrom(this.getAbsoluteTransform());
  68408. tmat.multiplyToRef(wm, tmat);
  68409. }
  68410. else {
  68411. tmat = this.getAbsoluteTransform();
  68412. }
  68413. result.x = tmat.m[12];
  68414. result.y = tmat.m[13];
  68415. result.z = tmat.m[14];
  68416. }
  68417. };
  68418. /**
  68419. * Get the absolute position of the bone (world space).
  68420. * @param mesh The mesh that this bone is attached to.
  68421. * @returns The absolute position of the bone
  68422. */
  68423. Bone.prototype.getAbsolutePosition = function (mesh) {
  68424. if (mesh === void 0) { mesh = null; }
  68425. var pos = BABYLON.Vector3.Zero();
  68426. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  68427. return pos;
  68428. };
  68429. /**
  68430. * Copy the absolute position of the bone (world space) to the result param.
  68431. * @param mesh The mesh that this bone is attached to.
  68432. * @param result The vector3 to copy the absolute position to.
  68433. */
  68434. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  68435. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  68436. };
  68437. /**
  68438. * Compute the absolute transforms of this bone and its children.
  68439. */
  68440. Bone.prototype.computeAbsoluteTransforms = function () {
  68441. if (this._parent) {
  68442. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  68443. }
  68444. else {
  68445. this._absoluteTransform.copyFrom(this._localMatrix);
  68446. var poseMatrix = this._skeleton.getPoseMatrix();
  68447. if (poseMatrix) {
  68448. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  68449. }
  68450. }
  68451. var children = this.children;
  68452. var len = children.length;
  68453. for (var i = 0; i < len; i++) {
  68454. children[i].computeAbsoluteTransforms();
  68455. }
  68456. };
  68457. Bone.prototype._syncScaleVector = function () {
  68458. var lm = this.getLocalMatrix();
  68459. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  68460. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  68461. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  68462. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  68463. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  68464. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  68465. this._scaleVector.x = xs * Math.sqrt(xsq);
  68466. this._scaleVector.y = ys * Math.sqrt(ysq);
  68467. this._scaleVector.z = zs * Math.sqrt(zsq);
  68468. if (this._parent) {
  68469. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  68470. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  68471. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  68472. }
  68473. 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);
  68474. };
  68475. /**
  68476. * Get the world direction from an axis that is in the local space of the bone.
  68477. * @param localAxis The local direction that is used to compute the world direction.
  68478. * @param mesh The mesh that this bone is attached to.
  68479. * @returns The world direction
  68480. */
  68481. Bone.prototype.getDirection = function (localAxis, mesh) {
  68482. if (mesh === void 0) { mesh = null; }
  68483. var result = BABYLON.Vector3.Zero();
  68484. this.getDirectionToRef(localAxis, mesh, result);
  68485. return result;
  68486. };
  68487. /**
  68488. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  68489. * @param localAxis The local direction that is used to compute the world direction.
  68490. * @param mesh The mesh that this bone is attached to.
  68491. * @param result The vector3 that the world direction will be copied to.
  68492. */
  68493. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  68494. if (mesh === void 0) { mesh = null; }
  68495. var wm = null;
  68496. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68497. if (mesh) {
  68498. wm = mesh.getWorldMatrix();
  68499. }
  68500. this._skeleton.computeAbsoluteTransforms();
  68501. var mat = Bone._tmpMats[0];
  68502. mat.copyFrom(this.getAbsoluteTransform());
  68503. if (mesh && wm) {
  68504. mat.multiplyToRef(wm, mat);
  68505. }
  68506. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  68507. result.normalize();
  68508. };
  68509. /**
  68510. * Get the euler rotation of the bone in local or world space.
  68511. * @param space The space that the rotation should be in.
  68512. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68513. * @returns The euler rotation
  68514. */
  68515. Bone.prototype.getRotation = function (space, mesh) {
  68516. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68517. if (mesh === void 0) { mesh = null; }
  68518. var result = BABYLON.Vector3.Zero();
  68519. this.getRotationToRef(space, mesh, result);
  68520. return result;
  68521. };
  68522. /**
  68523. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  68524. * @param space The space that the rotation should be in.
  68525. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68526. * @param result The vector3 that the rotation should be copied to.
  68527. */
  68528. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  68529. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68530. if (mesh === void 0) { mesh = null; }
  68531. var quat = Bone._tmpQuat;
  68532. this.getRotationQuaternionToRef(space, mesh, quat);
  68533. quat.toEulerAnglesToRef(result);
  68534. };
  68535. /**
  68536. * Get the quaternion rotation of the bone in either local or world space.
  68537. * @param space The space that the rotation should be in.
  68538. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68539. * @returns The quaternion rotation
  68540. */
  68541. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  68542. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68543. if (mesh === void 0) { mesh = null; }
  68544. var result = BABYLON.Quaternion.Identity();
  68545. this.getRotationQuaternionToRef(space, mesh, result);
  68546. return result;
  68547. };
  68548. /**
  68549. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  68550. * @param space The space that the rotation should be in.
  68551. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68552. * @param result The quaternion that the rotation should be copied to.
  68553. */
  68554. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  68555. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68556. if (mesh === void 0) { mesh = null; }
  68557. if (space == BABYLON.Space.LOCAL) {
  68558. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  68559. }
  68560. else {
  68561. var mat = Bone._tmpMats[0];
  68562. var amat = this.getAbsoluteTransform();
  68563. if (mesh) {
  68564. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  68565. }
  68566. else {
  68567. mat.copyFrom(amat);
  68568. }
  68569. mat.m[0] *= this._scalingDeterminant;
  68570. mat.m[1] *= this._scalingDeterminant;
  68571. mat.m[2] *= this._scalingDeterminant;
  68572. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  68573. }
  68574. };
  68575. /**
  68576. * Get the rotation matrix of the bone in local or world space.
  68577. * @param space The space that the rotation should be in.
  68578. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68579. * @returns The rotation matrix
  68580. */
  68581. Bone.prototype.getRotationMatrix = function (space, mesh) {
  68582. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68583. var result = BABYLON.Matrix.Identity();
  68584. this.getRotationMatrixToRef(space, mesh, result);
  68585. return result;
  68586. };
  68587. /**
  68588. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  68589. * @param space The space that the rotation should be in.
  68590. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68591. * @param result The quaternion that the rotation should be copied to.
  68592. */
  68593. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  68594. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68595. if (space == BABYLON.Space.LOCAL) {
  68596. this.getLocalMatrix().getRotationMatrixToRef(result);
  68597. }
  68598. else {
  68599. var mat = Bone._tmpMats[0];
  68600. var amat = this.getAbsoluteTransform();
  68601. if (mesh) {
  68602. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  68603. }
  68604. else {
  68605. mat.copyFrom(amat);
  68606. }
  68607. mat.m[0] *= this._scalingDeterminant;
  68608. mat.m[1] *= this._scalingDeterminant;
  68609. mat.m[2] *= this._scalingDeterminant;
  68610. mat.getRotationMatrixToRef(result);
  68611. }
  68612. };
  68613. /**
  68614. * Get the world position of a point that is in the local space of the bone.
  68615. * @param position The local position
  68616. * @param mesh The mesh that this bone is attached to.
  68617. * @returns The world position
  68618. */
  68619. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  68620. if (mesh === void 0) { mesh = null; }
  68621. var result = BABYLON.Vector3.Zero();
  68622. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  68623. return result;
  68624. };
  68625. /**
  68626. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  68627. * @param position The local position
  68628. * @param mesh The mesh that this bone is attached to.
  68629. * @param result The vector3 that the world position should be copied to.
  68630. */
  68631. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  68632. if (mesh === void 0) { mesh = null; }
  68633. var wm = null;
  68634. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68635. if (mesh) {
  68636. wm = mesh.getWorldMatrix();
  68637. }
  68638. this._skeleton.computeAbsoluteTransforms();
  68639. var tmat = Bone._tmpMats[0];
  68640. if (mesh && wm) {
  68641. tmat.copyFrom(this.getAbsoluteTransform());
  68642. tmat.multiplyToRef(wm, tmat);
  68643. }
  68644. else {
  68645. tmat = this.getAbsoluteTransform();
  68646. }
  68647. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  68648. };
  68649. /**
  68650. * Get the local position of a point that is in world space.
  68651. * @param position The world position
  68652. * @param mesh The mesh that this bone is attached to.
  68653. * @returns The local position
  68654. */
  68655. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  68656. if (mesh === void 0) { mesh = null; }
  68657. var result = BABYLON.Vector3.Zero();
  68658. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  68659. return result;
  68660. };
  68661. /**
  68662. * Get the local position of a point that is in world space and copy it to the result param.
  68663. * @param position The world position
  68664. * @param mesh The mesh that this bone is attached to.
  68665. * @param result The vector3 that the local position should be copied to.
  68666. */
  68667. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  68668. if (mesh === void 0) { mesh = null; }
  68669. var wm = null;
  68670. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68671. if (mesh) {
  68672. wm = mesh.getWorldMatrix();
  68673. }
  68674. this._skeleton.computeAbsoluteTransforms();
  68675. var tmat = Bone._tmpMats[0];
  68676. tmat.copyFrom(this.getAbsoluteTransform());
  68677. if (mesh && wm) {
  68678. tmat.multiplyToRef(wm, tmat);
  68679. }
  68680. tmat.invert();
  68681. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  68682. };
  68683. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68684. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  68685. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  68686. return Bone;
  68687. }(BABYLON.Node));
  68688. BABYLON.Bone = Bone;
  68689. })(BABYLON || (BABYLON = {}));
  68690. //# sourceMappingURL=babylon.bone.js.map
  68691. var BABYLON;
  68692. (function (BABYLON) {
  68693. var BoneIKController = /** @class */ (function () {
  68694. function BoneIKController(mesh, bone, options) {
  68695. this.targetPosition = BABYLON.Vector3.Zero();
  68696. this.poleTargetPosition = BABYLON.Vector3.Zero();
  68697. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  68698. this.poleAngle = 0;
  68699. this.slerpAmount = 1;
  68700. this._bone1Quat = BABYLON.Quaternion.Identity();
  68701. this._bone1Mat = BABYLON.Matrix.Identity();
  68702. this._bone2Ang = Math.PI;
  68703. this._maxAngle = Math.PI;
  68704. this._rightHandedSystem = false;
  68705. this._bendAxis = BABYLON.Vector3.Right();
  68706. this._slerping = false;
  68707. this._adjustRoll = 0;
  68708. this._bone2 = bone;
  68709. this._bone1 = bone.getParent();
  68710. if (!this._bone1) {
  68711. return;
  68712. }
  68713. this.mesh = mesh;
  68714. var bonePos = bone.getPosition();
  68715. if (bone.getAbsoluteTransform().determinant() > 0) {
  68716. this._rightHandedSystem = true;
  68717. this._bendAxis.x = 0;
  68718. this._bendAxis.y = 0;
  68719. this._bendAxis.z = -1;
  68720. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  68721. this._adjustRoll = Math.PI * .5;
  68722. this._bendAxis.z = 1;
  68723. }
  68724. }
  68725. if (this._bone1.length) {
  68726. var boneScale1 = this._bone1.getScale();
  68727. var boneScale2 = this._bone2.getScale();
  68728. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  68729. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  68730. }
  68731. else if (this._bone1.children[0]) {
  68732. mesh.computeWorldMatrix(true);
  68733. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  68734. var pos2 = this._bone2.getAbsolutePosition(mesh);
  68735. var pos3 = this._bone1.getAbsolutePosition(mesh);
  68736. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  68737. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  68738. }
  68739. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  68740. this.maxAngle = Math.PI;
  68741. if (options) {
  68742. if (options.targetMesh) {
  68743. this.targetMesh = options.targetMesh;
  68744. this.targetMesh.computeWorldMatrix(true);
  68745. }
  68746. if (options.poleTargetMesh) {
  68747. this.poleTargetMesh = options.poleTargetMesh;
  68748. this.poleTargetMesh.computeWorldMatrix(true);
  68749. }
  68750. else if (options.poleTargetBone) {
  68751. this.poleTargetBone = options.poleTargetBone;
  68752. }
  68753. else if (this._bone1.getParent()) {
  68754. this.poleTargetBone = this._bone1.getParent();
  68755. }
  68756. if (options.poleTargetLocalOffset) {
  68757. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  68758. }
  68759. if (options.poleAngle) {
  68760. this.poleAngle = options.poleAngle;
  68761. }
  68762. if (options.bendAxis) {
  68763. this._bendAxis.copyFrom(options.bendAxis);
  68764. }
  68765. if (options.maxAngle) {
  68766. this.maxAngle = options.maxAngle;
  68767. }
  68768. if (options.slerpAmount) {
  68769. this.slerpAmount = options.slerpAmount;
  68770. }
  68771. }
  68772. }
  68773. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  68774. get: function () {
  68775. return this._maxAngle;
  68776. },
  68777. set: function (value) {
  68778. this._setMaxAngle(value);
  68779. },
  68780. enumerable: true,
  68781. configurable: true
  68782. });
  68783. BoneIKController.prototype._setMaxAngle = function (ang) {
  68784. if (ang < 0) {
  68785. ang = 0;
  68786. }
  68787. if (ang > Math.PI || ang == undefined) {
  68788. ang = Math.PI;
  68789. }
  68790. this._maxAngle = ang;
  68791. var a = this._bone1Length;
  68792. var b = this._bone2Length;
  68793. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  68794. };
  68795. BoneIKController.prototype.update = function () {
  68796. var bone1 = this._bone1;
  68797. if (!bone1) {
  68798. return;
  68799. }
  68800. var target = this.targetPosition;
  68801. var poleTarget = this.poleTargetPosition;
  68802. var mat1 = BoneIKController._tmpMats[0];
  68803. var mat2 = BoneIKController._tmpMats[1];
  68804. if (this.targetMesh) {
  68805. target.copyFrom(this.targetMesh.getAbsolutePosition());
  68806. }
  68807. if (this.poleTargetBone) {
  68808. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  68809. }
  68810. else if (this.poleTargetMesh) {
  68811. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  68812. }
  68813. var bonePos = BoneIKController._tmpVecs[0];
  68814. var zaxis = BoneIKController._tmpVecs[1];
  68815. var xaxis = BoneIKController._tmpVecs[2];
  68816. var yaxis = BoneIKController._tmpVecs[3];
  68817. var upAxis = BoneIKController._tmpVecs[4];
  68818. var _tmpQuat = BoneIKController._tmpQuat;
  68819. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  68820. poleTarget.subtractToRef(bonePos, upAxis);
  68821. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  68822. upAxis.y = 1;
  68823. }
  68824. else {
  68825. upAxis.normalize();
  68826. }
  68827. target.subtractToRef(bonePos, yaxis);
  68828. yaxis.normalize();
  68829. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  68830. zaxis.normalize();
  68831. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  68832. xaxis.normalize();
  68833. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  68834. var a = this._bone1Length;
  68835. var b = this._bone2Length;
  68836. var c = BABYLON.Vector3.Distance(bonePos, target);
  68837. if (this._maxReach > 0) {
  68838. c = Math.min(this._maxReach, c);
  68839. }
  68840. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  68841. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  68842. if (acosa > 1) {
  68843. acosa = 1;
  68844. }
  68845. if (acosb > 1) {
  68846. acosb = 1;
  68847. }
  68848. if (acosa < -1) {
  68849. acosa = -1;
  68850. }
  68851. if (acosb < -1) {
  68852. acosb = -1;
  68853. }
  68854. var angA = Math.acos(acosa);
  68855. var angB = Math.acos(acosb);
  68856. var angC = -angA - angB;
  68857. if (this._rightHandedSystem) {
  68858. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  68859. mat2.multiplyToRef(mat1, mat1);
  68860. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  68861. mat2.multiplyToRef(mat1, mat1);
  68862. }
  68863. else {
  68864. var _tmpVec = BoneIKController._tmpVecs[5];
  68865. _tmpVec.copyFrom(this._bendAxis);
  68866. _tmpVec.x *= -1;
  68867. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  68868. mat2.multiplyToRef(mat1, mat1);
  68869. }
  68870. if (this.poleAngle) {
  68871. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  68872. mat1.multiplyToRef(mat2, mat1);
  68873. }
  68874. if (this._bone1) {
  68875. if (this.slerpAmount < 1) {
  68876. if (!this._slerping) {
  68877. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  68878. }
  68879. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  68880. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  68881. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  68882. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  68883. this._slerping = true;
  68884. }
  68885. else {
  68886. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  68887. this._bone1Mat.copyFrom(mat1);
  68888. this._slerping = false;
  68889. }
  68890. }
  68891. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  68892. this._bone2Ang = angC;
  68893. };
  68894. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68895. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  68896. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  68897. return BoneIKController;
  68898. }());
  68899. BABYLON.BoneIKController = BoneIKController;
  68900. })(BABYLON || (BABYLON = {}));
  68901. //# sourceMappingURL=babylon.boneIKController.js.map
  68902. var BABYLON;
  68903. (function (BABYLON) {
  68904. var BoneLookController = /** @class */ (function () {
  68905. /**
  68906. * Create a BoneLookController
  68907. * @param mesh the mesh that the bone belongs to
  68908. * @param bone the bone that will be looking to the target
  68909. * @param target the target Vector3 to look at
  68910. * @param settings optional settings:
  68911. * - maxYaw: the maximum angle the bone will yaw to
  68912. * - minYaw: the minimum angle the bone will yaw to
  68913. * - maxPitch: the maximum angle the bone will pitch to
  68914. * - minPitch: the minimum angle the bone will yaw to
  68915. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  68916. * - upAxis: the up axis of the coordinate system
  68917. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  68918. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  68919. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  68920. * - adjustYaw: used to make an adjustment to the yaw of the bone
  68921. * - adjustPitch: used to make an adjustment to the pitch of the bone
  68922. * - adjustRoll: used to make an adjustment to the roll of the bone
  68923. **/
  68924. function BoneLookController(mesh, bone, target, options) {
  68925. /**
  68926. * The up axis of the coordinate system that is used when the bone is rotated.
  68927. */
  68928. this.upAxis = BABYLON.Vector3.Up();
  68929. /**
  68930. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  68931. */
  68932. this.upAxisSpace = BABYLON.Space.LOCAL;
  68933. /**
  68934. * Used to make an adjustment to the yaw of the bone.
  68935. */
  68936. this.adjustYaw = 0;
  68937. /**
  68938. * Used to make an adjustment to the pitch of the bone.
  68939. */
  68940. this.adjustPitch = 0;
  68941. /**
  68942. * Used to make an adjustment to the roll of the bone.
  68943. */
  68944. this.adjustRoll = 0;
  68945. /**
  68946. * 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).
  68947. */
  68948. this.slerpAmount = 1;
  68949. this._boneQuat = BABYLON.Quaternion.Identity();
  68950. this._slerping = false;
  68951. this._firstFrameSkipped = false;
  68952. this._fowardAxis = BABYLON.Vector3.Forward();
  68953. this.mesh = mesh;
  68954. this.bone = bone;
  68955. this.target = target;
  68956. if (options) {
  68957. if (options.adjustYaw) {
  68958. this.adjustYaw = options.adjustYaw;
  68959. }
  68960. if (options.adjustPitch) {
  68961. this.adjustPitch = options.adjustPitch;
  68962. }
  68963. if (options.adjustRoll) {
  68964. this.adjustRoll = options.adjustRoll;
  68965. }
  68966. if (options.maxYaw != null) {
  68967. this.maxYaw = options.maxYaw;
  68968. }
  68969. else {
  68970. this.maxYaw = Math.PI;
  68971. }
  68972. if (options.minYaw != null) {
  68973. this.minYaw = options.minYaw;
  68974. }
  68975. else {
  68976. this.minYaw = -Math.PI;
  68977. }
  68978. if (options.maxPitch != null) {
  68979. this.maxPitch = options.maxPitch;
  68980. }
  68981. else {
  68982. this.maxPitch = Math.PI;
  68983. }
  68984. if (options.minPitch != null) {
  68985. this.minPitch = options.minPitch;
  68986. }
  68987. else {
  68988. this.minPitch = -Math.PI;
  68989. }
  68990. if (options.slerpAmount != null) {
  68991. this.slerpAmount = options.slerpAmount;
  68992. }
  68993. if (options.upAxis != null) {
  68994. this.upAxis = options.upAxis;
  68995. }
  68996. if (options.upAxisSpace != null) {
  68997. this.upAxisSpace = options.upAxisSpace;
  68998. }
  68999. if (options.yawAxis != null || options.pitchAxis != null) {
  69000. var newYawAxis = BABYLON.Axis.Y;
  69001. var newPitchAxis = BABYLON.Axis.X;
  69002. if (options.yawAxis != null) {
  69003. newYawAxis = options.yawAxis.clone();
  69004. newYawAxis.normalize();
  69005. }
  69006. if (options.pitchAxis != null) {
  69007. newPitchAxis = options.pitchAxis.clone();
  69008. newPitchAxis.normalize();
  69009. }
  69010. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  69011. this._transformYawPitch = BABYLON.Matrix.Identity();
  69012. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  69013. this._transformYawPitchInv = this._transformYawPitch.clone();
  69014. this._transformYawPitch.invert();
  69015. }
  69016. }
  69017. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  69018. this.upAxisSpace = BABYLON.Space.LOCAL;
  69019. }
  69020. }
  69021. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  69022. /**
  69023. * Get/set the minimum yaw angle that the bone can look to.
  69024. */
  69025. get: function () {
  69026. return this._minYaw;
  69027. },
  69028. set: function (value) {
  69029. this._minYaw = value;
  69030. this._minYawSin = Math.sin(value);
  69031. this._minYawCos = Math.cos(value);
  69032. if (this._maxYaw != null) {
  69033. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  69034. this._yawRange = this._maxYaw - this._minYaw;
  69035. }
  69036. },
  69037. enumerable: true,
  69038. configurable: true
  69039. });
  69040. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  69041. /**
  69042. * Get/set the maximum yaw angle that the bone can look to.
  69043. */
  69044. get: function () {
  69045. return this._maxYaw;
  69046. },
  69047. set: function (value) {
  69048. this._maxYaw = value;
  69049. this._maxYawSin = Math.sin(value);
  69050. this._maxYawCos = Math.cos(value);
  69051. if (this._minYaw != null) {
  69052. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  69053. this._yawRange = this._maxYaw - this._minYaw;
  69054. }
  69055. },
  69056. enumerable: true,
  69057. configurable: true
  69058. });
  69059. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  69060. /**
  69061. * Get/set the minimum pitch angle that the bone can look to.
  69062. */
  69063. get: function () {
  69064. return this._minPitch;
  69065. },
  69066. set: function (value) {
  69067. this._minPitch = value;
  69068. this._minPitchTan = Math.tan(value);
  69069. },
  69070. enumerable: true,
  69071. configurable: true
  69072. });
  69073. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  69074. /**
  69075. * Get/set the maximum pitch angle that the bone can look to.
  69076. */
  69077. get: function () {
  69078. return this._maxPitch;
  69079. },
  69080. set: function (value) {
  69081. this._maxPitch = value;
  69082. this._maxPitchTan = Math.tan(value);
  69083. },
  69084. enumerable: true,
  69085. configurable: true
  69086. });
  69087. /**
  69088. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  69089. */
  69090. BoneLookController.prototype.update = function () {
  69091. //skip the first frame when slerping so that the mesh rotation is correct
  69092. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  69093. this._firstFrameSkipped = true;
  69094. return;
  69095. }
  69096. var bone = this.bone;
  69097. var bonePos = BoneLookController._tmpVecs[0];
  69098. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  69099. var target = this.target;
  69100. var _tmpMat1 = BoneLookController._tmpMats[0];
  69101. var _tmpMat2 = BoneLookController._tmpMats[1];
  69102. var mesh = this.mesh;
  69103. var parentBone = bone.getParent();
  69104. var upAxis = BoneLookController._tmpVecs[1];
  69105. upAxis.copyFrom(this.upAxis);
  69106. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  69107. if (this._transformYawPitch) {
  69108. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  69109. }
  69110. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  69111. }
  69112. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  69113. mesh.getDirectionToRef(upAxis, upAxis);
  69114. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  69115. upAxis.normalize();
  69116. }
  69117. }
  69118. var checkYaw = false;
  69119. var checkPitch = false;
  69120. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  69121. checkYaw = true;
  69122. }
  69123. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  69124. checkPitch = true;
  69125. }
  69126. if (checkYaw || checkPitch) {
  69127. var spaceMat = BoneLookController._tmpMats[2];
  69128. var spaceMatInv = BoneLookController._tmpMats[3];
  69129. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  69130. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  69131. }
  69132. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  69133. spaceMat.copyFrom(mesh.getWorldMatrix());
  69134. }
  69135. else {
  69136. var forwardAxis = BoneLookController._tmpVecs[2];
  69137. forwardAxis.copyFrom(this._fowardAxis);
  69138. if (this._transformYawPitch) {
  69139. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  69140. }
  69141. if (parentBone) {
  69142. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  69143. }
  69144. else {
  69145. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  69146. }
  69147. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  69148. rightAxis.normalize();
  69149. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  69150. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  69151. }
  69152. spaceMat.invertToRef(spaceMatInv);
  69153. var xzlen = null;
  69154. if (checkPitch) {
  69155. var localTarget = BoneLookController._tmpVecs[3];
  69156. target.subtractToRef(bonePos, localTarget);
  69157. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  69158. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  69159. var pitch = Math.atan2(localTarget.y, xzlen);
  69160. var newPitch = pitch;
  69161. if (pitch > this._maxPitch) {
  69162. localTarget.y = this._maxPitchTan * xzlen;
  69163. newPitch = this._maxPitch;
  69164. }
  69165. else if (pitch < this._minPitch) {
  69166. localTarget.y = this._minPitchTan * xzlen;
  69167. newPitch = this._minPitch;
  69168. }
  69169. if (pitch != newPitch) {
  69170. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  69171. localTarget.addInPlace(bonePos);
  69172. target = localTarget;
  69173. }
  69174. }
  69175. if (checkYaw) {
  69176. var localTarget = BoneLookController._tmpVecs[4];
  69177. target.subtractToRef(bonePos, localTarget);
  69178. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  69179. var yaw = Math.atan2(localTarget.x, localTarget.z);
  69180. var newYaw = yaw;
  69181. if (yaw > this._maxYaw || yaw < this._minYaw) {
  69182. if (xzlen == null) {
  69183. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  69184. }
  69185. if (this._yawRange > Math.PI) {
  69186. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  69187. localTarget.z = this._maxYawCos * xzlen;
  69188. localTarget.x = this._maxYawSin * xzlen;
  69189. newYaw = this._maxYaw;
  69190. }
  69191. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  69192. localTarget.z = this._minYawCos * xzlen;
  69193. localTarget.x = this._minYawSin * xzlen;
  69194. newYaw = this._minYaw;
  69195. }
  69196. }
  69197. else {
  69198. if (yaw > this._maxYaw) {
  69199. localTarget.z = this._maxYawCos * xzlen;
  69200. localTarget.x = this._maxYawSin * xzlen;
  69201. newYaw = this._maxYaw;
  69202. }
  69203. else if (yaw < this._minYaw) {
  69204. localTarget.z = this._minYawCos * xzlen;
  69205. localTarget.x = this._minYawSin * xzlen;
  69206. newYaw = this._minYaw;
  69207. }
  69208. }
  69209. }
  69210. if (this._slerping && this._yawRange > Math.PI) {
  69211. //are we going to be crossing into the min/max region?
  69212. var boneFwd = BoneLookController._tmpVecs[8];
  69213. boneFwd.copyFrom(BABYLON.Axis.Z);
  69214. if (this._transformYawPitch) {
  69215. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  69216. }
  69217. var boneRotMat = BoneLookController._tmpMats[4];
  69218. this._boneQuat.toRotationMatrix(boneRotMat);
  69219. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  69220. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  69221. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  69222. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  69223. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  69224. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  69225. if (angBtwTar > angBtwMidYaw) {
  69226. if (xzlen == null) {
  69227. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  69228. }
  69229. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  69230. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  69231. if (angBtwMin < angBtwMax) {
  69232. newYaw = boneYaw + Math.PI * .75;
  69233. localTarget.z = Math.cos(newYaw) * xzlen;
  69234. localTarget.x = Math.sin(newYaw) * xzlen;
  69235. }
  69236. else {
  69237. newYaw = boneYaw - Math.PI * .75;
  69238. localTarget.z = Math.cos(newYaw) * xzlen;
  69239. localTarget.x = Math.sin(newYaw) * xzlen;
  69240. }
  69241. }
  69242. }
  69243. if (yaw != newYaw) {
  69244. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  69245. localTarget.addInPlace(bonePos);
  69246. target = localTarget;
  69247. }
  69248. }
  69249. }
  69250. var zaxis = BoneLookController._tmpVecs[5];
  69251. var xaxis = BoneLookController._tmpVecs[6];
  69252. var yaxis = BoneLookController._tmpVecs[7];
  69253. var _tmpQuat = BoneLookController._tmpQuat;
  69254. target.subtractToRef(bonePos, zaxis);
  69255. zaxis.normalize();
  69256. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  69257. xaxis.normalize();
  69258. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  69259. yaxis.normalize();
  69260. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  69261. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  69262. return;
  69263. }
  69264. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  69265. return;
  69266. }
  69267. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  69268. return;
  69269. }
  69270. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  69271. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  69272. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  69273. }
  69274. if (this.slerpAmount < 1) {
  69275. if (!this._slerping) {
  69276. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  69277. }
  69278. if (this._transformYawPitch) {
  69279. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  69280. }
  69281. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  69282. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  69283. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  69284. this._slerping = true;
  69285. }
  69286. else {
  69287. if (this._transformYawPitch) {
  69288. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  69289. }
  69290. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  69291. this._slerping = false;
  69292. }
  69293. };
  69294. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  69295. var angDiff = ang2 - ang1;
  69296. angDiff %= Math.PI * 2;
  69297. if (angDiff > Math.PI) {
  69298. angDiff -= Math.PI * 2;
  69299. }
  69300. else if (angDiff < -Math.PI) {
  69301. angDiff += Math.PI * 2;
  69302. }
  69303. return angDiff;
  69304. };
  69305. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  69306. ang1 %= (2 * Math.PI);
  69307. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  69308. ang2 %= (2 * Math.PI);
  69309. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  69310. var ab = 0;
  69311. if (ang1 < ang2) {
  69312. ab = ang2 - ang1;
  69313. }
  69314. else {
  69315. ab = ang1 - ang2;
  69316. }
  69317. if (ab > Math.PI) {
  69318. ab = Math.PI * 2 - ab;
  69319. }
  69320. return ab;
  69321. };
  69322. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  69323. ang %= (2 * Math.PI);
  69324. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  69325. ang1 %= (2 * Math.PI);
  69326. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  69327. ang2 %= (2 * Math.PI);
  69328. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  69329. if (ang1 < ang2) {
  69330. if (ang > ang1 && ang < ang2) {
  69331. return true;
  69332. }
  69333. }
  69334. else {
  69335. if (ang > ang2 && ang < ang1) {
  69336. return true;
  69337. }
  69338. }
  69339. return false;
  69340. };
  69341. 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()];
  69342. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  69343. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  69344. return BoneLookController;
  69345. }());
  69346. BABYLON.BoneLookController = BoneLookController;
  69347. })(BABYLON || (BABYLON = {}));
  69348. //# sourceMappingURL=babylon.boneLookController.js.map
  69349. var BABYLON;
  69350. (function (BABYLON) {
  69351. var Skeleton = /** @class */ (function () {
  69352. function Skeleton(name, id, scene) {
  69353. this.name = name;
  69354. this.id = id;
  69355. this.bones = new Array();
  69356. this.needInitialSkinMatrix = false;
  69357. this._isDirty = true;
  69358. this._meshesWithPoseMatrix = new Array();
  69359. this._identity = BABYLON.Matrix.Identity();
  69360. this._ranges = {};
  69361. this._lastAbsoluteTransformsUpdateId = -1;
  69362. // Events
  69363. /**
  69364. * An event triggered before computing the skeleton's matrices
  69365. * @type {BABYLON.Observable}
  69366. */
  69367. this.onBeforeComputeObservable = new BABYLON.Observable();
  69368. this.bones = [];
  69369. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  69370. scene.skeletons.push(this);
  69371. //make sure it will recalculate the matrix next time prepare is called.
  69372. this._isDirty = true;
  69373. }
  69374. // Members
  69375. Skeleton.prototype.getTransformMatrices = function (mesh) {
  69376. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  69377. return mesh._bonesTransformMatrices;
  69378. }
  69379. if (!this._transformMatrices) {
  69380. this.prepare();
  69381. }
  69382. return this._transformMatrices;
  69383. };
  69384. Skeleton.prototype.getScene = function () {
  69385. return this._scene;
  69386. };
  69387. // Methods
  69388. /**
  69389. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  69390. */
  69391. Skeleton.prototype.toString = function (fullDetails) {
  69392. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  69393. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  69394. if (fullDetails) {
  69395. ret += ", Ranges: {";
  69396. var first = true;
  69397. for (var name_1 in this._ranges) {
  69398. if (first) {
  69399. ret += ", ";
  69400. first = false;
  69401. }
  69402. ret += name_1;
  69403. }
  69404. ret += "}";
  69405. }
  69406. return ret;
  69407. };
  69408. /**
  69409. * Get bone's index searching by name
  69410. * @param {string} name is bone's name to search for
  69411. * @return {number} Indice of the bone. Returns -1 if not found
  69412. */
  69413. Skeleton.prototype.getBoneIndexByName = function (name) {
  69414. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  69415. if (this.bones[boneIndex].name === name) {
  69416. return boneIndex;
  69417. }
  69418. }
  69419. return -1;
  69420. };
  69421. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  69422. // check name not already in use
  69423. if (!this._ranges[name]) {
  69424. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  69425. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  69426. if (this.bones[i].animations[0]) {
  69427. this.bones[i].animations[0].createRange(name, from, to);
  69428. }
  69429. }
  69430. }
  69431. };
  69432. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  69433. if (deleteFrames === void 0) { deleteFrames = true; }
  69434. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  69435. if (this.bones[i].animations[0]) {
  69436. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  69437. }
  69438. }
  69439. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  69440. };
  69441. Skeleton.prototype.getAnimationRange = function (name) {
  69442. return this._ranges[name];
  69443. };
  69444. /**
  69445. * Returns as an Array, all AnimationRanges defined on this skeleton
  69446. */
  69447. Skeleton.prototype.getAnimationRanges = function () {
  69448. var animationRanges = [];
  69449. var name;
  69450. var i = 0;
  69451. for (name in this._ranges) {
  69452. animationRanges[i] = this._ranges[name];
  69453. i++;
  69454. }
  69455. return animationRanges;
  69456. };
  69457. /**
  69458. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  69459. */
  69460. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  69461. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  69462. if (this._ranges[name] || !source.getAnimationRange(name)) {
  69463. return false;
  69464. }
  69465. var ret = true;
  69466. var frameOffset = this._getHighestAnimationFrame() + 1;
  69467. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  69468. var boneDict = {};
  69469. var sourceBones = source.bones;
  69470. var nBones;
  69471. var i;
  69472. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  69473. boneDict[sourceBones[i].name] = sourceBones[i];
  69474. }
  69475. if (this.bones.length !== sourceBones.length) {
  69476. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  69477. ret = false;
  69478. }
  69479. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  69480. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  69481. var boneName = this.bones[i].name;
  69482. var sourceBone = boneDict[boneName];
  69483. if (sourceBone) {
  69484. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  69485. }
  69486. else {
  69487. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  69488. ret = false;
  69489. }
  69490. }
  69491. // do not call createAnimationRange(), since it also is done to bones, which was already done
  69492. var range = source.getAnimationRange(name);
  69493. if (range) {
  69494. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  69495. }
  69496. return ret;
  69497. };
  69498. Skeleton.prototype.returnToRest = function () {
  69499. for (var index = 0; index < this.bones.length; index++) {
  69500. this.bones[index].returnToRest();
  69501. }
  69502. };
  69503. Skeleton.prototype._getHighestAnimationFrame = function () {
  69504. var ret = 0;
  69505. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  69506. if (this.bones[i].animations[0]) {
  69507. var highest = this.bones[i].animations[0].getHighestFrame();
  69508. if (ret < highest) {
  69509. ret = highest;
  69510. }
  69511. }
  69512. }
  69513. return ret;
  69514. };
  69515. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  69516. var range = this.getAnimationRange(name);
  69517. if (!range) {
  69518. return null;
  69519. }
  69520. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  69521. };
  69522. Skeleton.prototype._markAsDirty = function () {
  69523. this._isDirty = true;
  69524. };
  69525. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  69526. this._meshesWithPoseMatrix.push(mesh);
  69527. };
  69528. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  69529. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  69530. if (index > -1) {
  69531. this._meshesWithPoseMatrix.splice(index, 1);
  69532. }
  69533. };
  69534. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  69535. this.onBeforeComputeObservable.notifyObservers(this);
  69536. for (var index = 0; index < this.bones.length; index++) {
  69537. var bone = this.bones[index];
  69538. var parentBone = bone.getParent();
  69539. if (parentBone) {
  69540. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  69541. }
  69542. else {
  69543. if (initialSkinMatrix) {
  69544. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  69545. }
  69546. else {
  69547. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  69548. }
  69549. }
  69550. if (bone._index !== -1) {
  69551. var mappedIndex = bone._index === null ? index : bone._index;
  69552. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  69553. }
  69554. }
  69555. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  69556. };
  69557. Skeleton.prototype.prepare = function () {
  69558. if (!this._isDirty) {
  69559. return;
  69560. }
  69561. if (this.needInitialSkinMatrix) {
  69562. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  69563. var mesh = this._meshesWithPoseMatrix[index];
  69564. var poseMatrix = mesh.getPoseMatrix();
  69565. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  69566. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  69567. }
  69568. if (this._synchronizedWithMesh !== mesh) {
  69569. this._synchronizedWithMesh = mesh;
  69570. // Prepare bones
  69571. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  69572. var bone = this.bones[boneIndex];
  69573. if (!bone.getParent()) {
  69574. var matrix = bone.getBaseMatrix();
  69575. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  69576. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  69577. }
  69578. }
  69579. }
  69580. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  69581. }
  69582. }
  69583. else {
  69584. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  69585. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  69586. }
  69587. this._computeTransformMatrices(this._transformMatrices, null);
  69588. }
  69589. this._isDirty = false;
  69590. this._scene._activeBones.addCount(this.bones.length, false);
  69591. };
  69592. Skeleton.prototype.getAnimatables = function () {
  69593. if (!this._animatables || this._animatables.length !== this.bones.length) {
  69594. this._animatables = [];
  69595. for (var index = 0; index < this.bones.length; index++) {
  69596. this._animatables.push(this.bones[index]);
  69597. }
  69598. }
  69599. return this._animatables;
  69600. };
  69601. Skeleton.prototype.clone = function (name, id) {
  69602. var result = new Skeleton(name, id || name, this._scene);
  69603. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  69604. for (var index = 0; index < this.bones.length; index++) {
  69605. var source = this.bones[index];
  69606. var parentBone = null;
  69607. var parent_1 = source.getParent();
  69608. if (parent_1) {
  69609. var parentIndex = this.bones.indexOf(parent_1);
  69610. parentBone = result.bones[parentIndex];
  69611. }
  69612. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  69613. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  69614. }
  69615. if (this._ranges) {
  69616. result._ranges = {};
  69617. for (var rangeName in this._ranges) {
  69618. var range = this._ranges[rangeName];
  69619. if (range) {
  69620. result._ranges[rangeName] = range.clone();
  69621. }
  69622. }
  69623. }
  69624. this._isDirty = true;
  69625. return result;
  69626. };
  69627. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  69628. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  69629. this.bones.forEach(function (bone) {
  69630. bone.animations.forEach(function (animation) {
  69631. animation.enableBlending = true;
  69632. animation.blendingSpeed = blendingSpeed;
  69633. });
  69634. });
  69635. };
  69636. Skeleton.prototype.dispose = function () {
  69637. this._meshesWithPoseMatrix = [];
  69638. // Animations
  69639. this.getScene().stopAnimation(this);
  69640. // Remove from scene
  69641. this.getScene().removeSkeleton(this);
  69642. };
  69643. Skeleton.prototype.serialize = function () {
  69644. var serializationObject = {};
  69645. serializationObject.name = this.name;
  69646. serializationObject.id = this.id;
  69647. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  69648. serializationObject.bones = [];
  69649. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  69650. for (var index = 0; index < this.bones.length; index++) {
  69651. var bone = this.bones[index];
  69652. var parent_2 = bone.getParent();
  69653. var serializedBone = {
  69654. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  69655. name: bone.name,
  69656. matrix: bone.getBaseMatrix().toArray(),
  69657. rest: bone.getRestPose().toArray()
  69658. };
  69659. serializationObject.bones.push(serializedBone);
  69660. if (bone.length) {
  69661. serializedBone.length = bone.length;
  69662. }
  69663. if (bone.animations && bone.animations.length > 0) {
  69664. serializedBone.animation = bone.animations[0].serialize();
  69665. }
  69666. serializationObject.ranges = [];
  69667. for (var name in this._ranges) {
  69668. var source = this._ranges[name];
  69669. if (!source) {
  69670. continue;
  69671. }
  69672. var range = {};
  69673. range.name = name;
  69674. range.from = source.from;
  69675. range.to = source.to;
  69676. serializationObject.ranges.push(range);
  69677. }
  69678. }
  69679. return serializationObject;
  69680. };
  69681. Skeleton.Parse = function (parsedSkeleton, scene) {
  69682. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  69683. if (parsedSkeleton.dimensionsAtRest) {
  69684. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  69685. }
  69686. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  69687. var index;
  69688. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  69689. var parsedBone = parsedSkeleton.bones[index];
  69690. var parentBone = null;
  69691. if (parsedBone.parentBoneIndex > -1) {
  69692. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  69693. }
  69694. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  69695. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  69696. if (parsedBone.length) {
  69697. bone.length = parsedBone.length;
  69698. }
  69699. if (parsedBone.animation) {
  69700. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  69701. }
  69702. }
  69703. // placed after bones, so createAnimationRange can cascade down
  69704. if (parsedSkeleton.ranges) {
  69705. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  69706. var data = parsedSkeleton.ranges[index];
  69707. skeleton.createAnimationRange(data.name, data.from, data.to);
  69708. }
  69709. }
  69710. return skeleton;
  69711. };
  69712. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  69713. if (forceUpdate === void 0) { forceUpdate = false; }
  69714. var renderId = this._scene.getRenderId();
  69715. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  69716. this.bones[0].computeAbsoluteTransforms();
  69717. this._lastAbsoluteTransformsUpdateId = renderId;
  69718. }
  69719. };
  69720. Skeleton.prototype.getPoseMatrix = function () {
  69721. var poseMatrix = null;
  69722. if (this._meshesWithPoseMatrix.length > 0) {
  69723. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  69724. }
  69725. return poseMatrix;
  69726. };
  69727. Skeleton.prototype.sortBones = function () {
  69728. var bones = new Array();
  69729. var visited = new Array(this.bones.length);
  69730. for (var index = 0; index < this.bones.length; index++) {
  69731. this._sortBones(index, bones, visited);
  69732. }
  69733. this.bones = bones;
  69734. };
  69735. Skeleton.prototype._sortBones = function (index, bones, visited) {
  69736. if (visited[index]) {
  69737. return;
  69738. }
  69739. visited[index] = true;
  69740. var bone = this.bones[index];
  69741. if (bone._index === undefined) {
  69742. bone._index = index;
  69743. }
  69744. var parentBone = bone.getParent();
  69745. if (parentBone) {
  69746. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  69747. }
  69748. bones.push(bone);
  69749. };
  69750. return Skeleton;
  69751. }());
  69752. BABYLON.Skeleton = Skeleton;
  69753. })(BABYLON || (BABYLON = {}));
  69754. //# sourceMappingURL=babylon.skeleton.js.map
  69755. var BABYLON;
  69756. (function (BABYLON) {
  69757. var SphericalPolynomial = /** @class */ (function () {
  69758. function SphericalPolynomial() {
  69759. this.x = BABYLON.Vector3.Zero();
  69760. this.y = BABYLON.Vector3.Zero();
  69761. this.z = BABYLON.Vector3.Zero();
  69762. this.xx = BABYLON.Vector3.Zero();
  69763. this.yy = BABYLON.Vector3.Zero();
  69764. this.zz = BABYLON.Vector3.Zero();
  69765. this.xy = BABYLON.Vector3.Zero();
  69766. this.yz = BABYLON.Vector3.Zero();
  69767. this.zx = BABYLON.Vector3.Zero();
  69768. }
  69769. SphericalPolynomial.prototype.addAmbient = function (color) {
  69770. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  69771. this.xx = this.xx.add(colorVector);
  69772. this.yy = this.yy.add(colorVector);
  69773. this.zz = this.zz.add(colorVector);
  69774. };
  69775. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  69776. var result = new SphericalPolynomial();
  69777. result.x = harmonics.L11.scale(1.02333);
  69778. result.y = harmonics.L1_1.scale(1.02333);
  69779. result.z = harmonics.L10.scale(1.02333);
  69780. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  69781. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  69782. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  69783. result.yz = harmonics.L2_1.scale(0.858086);
  69784. result.zx = harmonics.L21.scale(0.858086);
  69785. result.xy = harmonics.L2_2.scale(0.858086);
  69786. result.scale(1.0 / Math.PI);
  69787. return result;
  69788. };
  69789. SphericalPolynomial.prototype.scale = function (scale) {
  69790. this.x = this.x.scale(scale);
  69791. this.y = this.y.scale(scale);
  69792. this.z = this.z.scale(scale);
  69793. this.xx = this.xx.scale(scale);
  69794. this.yy = this.yy.scale(scale);
  69795. this.zz = this.zz.scale(scale);
  69796. this.yz = this.yz.scale(scale);
  69797. this.zx = this.zx.scale(scale);
  69798. this.xy = this.xy.scale(scale);
  69799. };
  69800. return SphericalPolynomial;
  69801. }());
  69802. BABYLON.SphericalPolynomial = SphericalPolynomial;
  69803. var SphericalHarmonics = /** @class */ (function () {
  69804. function SphericalHarmonics() {
  69805. this.L00 = BABYLON.Vector3.Zero();
  69806. this.L1_1 = BABYLON.Vector3.Zero();
  69807. this.L10 = BABYLON.Vector3.Zero();
  69808. this.L11 = BABYLON.Vector3.Zero();
  69809. this.L2_2 = BABYLON.Vector3.Zero();
  69810. this.L2_1 = BABYLON.Vector3.Zero();
  69811. this.L20 = BABYLON.Vector3.Zero();
  69812. this.L21 = BABYLON.Vector3.Zero();
  69813. this.L22 = BABYLON.Vector3.Zero();
  69814. }
  69815. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  69816. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  69817. var c = colorVector.scale(deltaSolidAngle);
  69818. this.L00 = this.L00.add(c.scale(0.282095));
  69819. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  69820. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  69821. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  69822. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  69823. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  69824. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  69825. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  69826. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  69827. };
  69828. SphericalHarmonics.prototype.scale = function (scale) {
  69829. this.L00 = this.L00.scale(scale);
  69830. this.L1_1 = this.L1_1.scale(scale);
  69831. this.L10 = this.L10.scale(scale);
  69832. this.L11 = this.L11.scale(scale);
  69833. this.L2_2 = this.L2_2.scale(scale);
  69834. this.L2_1 = this.L2_1.scale(scale);
  69835. this.L20 = this.L20.scale(scale);
  69836. this.L21 = this.L21.scale(scale);
  69837. this.L22 = this.L22.scale(scale);
  69838. };
  69839. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  69840. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  69841. //
  69842. // E_lm = A_l * L_lm
  69843. //
  69844. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  69845. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  69846. // the scaling factors are given in equation 9.
  69847. // Constant (Band 0)
  69848. this.L00 = this.L00.scale(3.141593);
  69849. // Linear (Band 1)
  69850. this.L1_1 = this.L1_1.scale(2.094395);
  69851. this.L10 = this.L10.scale(2.094395);
  69852. this.L11 = this.L11.scale(2.094395);
  69853. // Quadratic (Band 2)
  69854. this.L2_2 = this.L2_2.scale(0.785398);
  69855. this.L2_1 = this.L2_1.scale(0.785398);
  69856. this.L20 = this.L20.scale(0.785398);
  69857. this.L21 = this.L21.scale(0.785398);
  69858. this.L22 = this.L22.scale(0.785398);
  69859. };
  69860. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  69861. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  69862. // L = (1/pi) * E * rho
  69863. //
  69864. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  69865. this.scale(1.0 / Math.PI);
  69866. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  69867. // (The pixel shader must apply albedo after texture fetches, etc).
  69868. };
  69869. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  69870. var result = new SphericalHarmonics();
  69871. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  69872. result.L1_1 = polynomial.y.scale(0.977204);
  69873. result.L10 = polynomial.z.scale(0.977204);
  69874. result.L11 = polynomial.x.scale(0.977204);
  69875. result.L2_2 = polynomial.xy.scale(1.16538);
  69876. result.L2_1 = polynomial.yz.scale(1.16538);
  69877. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  69878. result.L21 = polynomial.zx.scale(1.16538);
  69879. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  69880. result.scale(Math.PI);
  69881. return result;
  69882. };
  69883. return SphericalHarmonics;
  69884. }());
  69885. BABYLON.SphericalHarmonics = SphericalHarmonics;
  69886. })(BABYLON || (BABYLON = {}));
  69887. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  69888. var BABYLON;
  69889. (function (BABYLON) {
  69890. var FileFaceOrientation = /** @class */ (function () {
  69891. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  69892. this.name = name;
  69893. this.worldAxisForNormal = worldAxisForNormal;
  69894. this.worldAxisForFileX = worldAxisForFileX;
  69895. this.worldAxisForFileY = worldAxisForFileY;
  69896. }
  69897. return FileFaceOrientation;
  69898. }());
  69899. ;
  69900. /**
  69901. * Helper class dealing with the extraction of spherical polynomial dataArray
  69902. * from a cube map.
  69903. */
  69904. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  69905. function CubeMapToSphericalPolynomialTools() {
  69906. }
  69907. /**
  69908. * Converts a texture to the according Spherical Polynomial data.
  69909. * This extracts the first 3 orders only as they are the only one used in the lighting.
  69910. *
  69911. * @param texture The texture to extract the information from.
  69912. * @return The Spherical Polynomial data.
  69913. */
  69914. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  69915. if (!texture.isCube) {
  69916. // Only supports cube Textures currently.
  69917. return null;
  69918. }
  69919. var size = texture.getSize().width;
  69920. var right = texture.readPixels(0);
  69921. var left = texture.readPixels(1);
  69922. var up;
  69923. var down;
  69924. if (texture.isRenderTarget) {
  69925. up = texture.readPixels(3);
  69926. down = texture.readPixels(2);
  69927. }
  69928. else {
  69929. up = texture.readPixels(2);
  69930. down = texture.readPixels(3);
  69931. }
  69932. var front = texture.readPixels(4);
  69933. var back = texture.readPixels(5);
  69934. var gammaSpace = texture.gammaSpace;
  69935. // Always read as RGBA.
  69936. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  69937. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69938. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  69939. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69940. }
  69941. var cubeInfo = {
  69942. size: size,
  69943. right: right,
  69944. left: left,
  69945. up: up,
  69946. down: down,
  69947. front: front,
  69948. back: back,
  69949. format: format,
  69950. type: type,
  69951. gammaSpace: gammaSpace,
  69952. };
  69953. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  69954. };
  69955. /**
  69956. * Converts a cubemap to the according Spherical Polynomial data.
  69957. * This extracts the first 3 orders only as they are the only one used in the lighting.
  69958. *
  69959. * @param cubeInfo The Cube map to extract the information from.
  69960. * @return The Spherical Polynomial data.
  69961. */
  69962. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  69963. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  69964. var totalSolidAngle = 0.0;
  69965. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  69966. var du = 2.0 / cubeInfo.size;
  69967. var dv = du;
  69968. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  69969. var minUV = du * 0.5 - 1.0;
  69970. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  69971. var fileFace = this.FileFaces[faceIndex];
  69972. var dataArray = cubeInfo[fileFace.name];
  69973. var v = minUV;
  69974. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  69975. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  69976. // Because SP is still linear, so summation is fine in that basis.
  69977. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  69978. for (var y = 0; y < cubeInfo.size; y++) {
  69979. var u = minUV;
  69980. for (var x = 0; x < cubeInfo.size; x++) {
  69981. // World direction (not normalised)
  69982. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  69983. worldDirection.normalize();
  69984. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  69985. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  69986. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  69987. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  69988. // Handle Integer types.
  69989. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  69990. r /= 255;
  69991. g /= 255;
  69992. b /= 255;
  69993. }
  69994. // Handle Gamma space textures.
  69995. if (cubeInfo.gammaSpace) {
  69996. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  69997. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  69998. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  69999. }
  70000. var color = new BABYLON.Color3(r, g, b);
  70001. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  70002. totalSolidAngle += deltaSolidAngle;
  70003. u += du;
  70004. }
  70005. v += dv;
  70006. }
  70007. }
  70008. // Solid angle for entire sphere is 4*pi
  70009. var sphereSolidAngle = 4.0 * Math.PI;
  70010. // Adjust the solid angle to allow for how many faces we processed.
  70011. var facesProcessed = 6.0;
  70012. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  70013. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  70014. // This is needed because the numerical integration over the cube uses a
  70015. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  70016. // and also to compensate for accumulative error due to float precision in the summation.
  70017. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  70018. sphericalHarmonics.scale(correctionFactor);
  70019. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  70020. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  70021. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  70022. };
  70023. CubeMapToSphericalPolynomialTools.FileFaces = [
  70024. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  70025. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  70026. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  70027. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  70028. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  70029. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  70030. ];
  70031. return CubeMapToSphericalPolynomialTools;
  70032. }());
  70033. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  70034. })(BABYLON || (BABYLON = {}));
  70035. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  70036. var BABYLON;
  70037. (function (BABYLON) {
  70038. /**
  70039. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  70040. */
  70041. var PanoramaToCubeMapTools = /** @class */ (function () {
  70042. function PanoramaToCubeMapTools() {
  70043. }
  70044. /**
  70045. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  70046. *
  70047. * @param float32Array The source data.
  70048. * @param inputWidth The width of the input panorama.
  70049. * @param inputhHeight The height of the input panorama.
  70050. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  70051. * @return The cubemap data
  70052. */
  70053. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  70054. if (!float32Array) {
  70055. throw "ConvertPanoramaToCubemap: input cannot be null";
  70056. }
  70057. if (float32Array.length != inputWidth * inputHeight * 3) {
  70058. throw "ConvertPanoramaToCubemap: input size is wrong";
  70059. }
  70060. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  70061. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  70062. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  70063. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  70064. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  70065. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  70066. return {
  70067. front: textureFront,
  70068. back: textureBack,
  70069. left: textureLeft,
  70070. right: textureRight,
  70071. up: textureUp,
  70072. down: textureDown,
  70073. size: size,
  70074. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  70075. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  70076. gammaSpace: false,
  70077. };
  70078. };
  70079. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  70080. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  70081. var textureArray = new Float32Array(buffer);
  70082. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  70083. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  70084. var dy = 1 / texSize;
  70085. var fy = 0;
  70086. for (var y = 0; y < texSize; y++) {
  70087. var xv1 = faceData[0];
  70088. var xv2 = faceData[2];
  70089. for (var x = 0; x < texSize; x++) {
  70090. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  70091. v.normalize();
  70092. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  70093. // 3 channels per pixels
  70094. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  70095. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  70096. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  70097. xv1 = xv1.add(rotDX1);
  70098. xv2 = xv2.add(rotDX2);
  70099. }
  70100. fy += dy;
  70101. }
  70102. return textureArray;
  70103. };
  70104. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  70105. var theta = Math.atan2(vDir.z, vDir.x);
  70106. var phi = Math.acos(vDir.y);
  70107. while (theta < -Math.PI)
  70108. theta += 2 * Math.PI;
  70109. while (theta > Math.PI)
  70110. theta -= 2 * Math.PI;
  70111. var dx = theta / Math.PI;
  70112. var dy = phi / Math.PI;
  70113. // recenter.
  70114. dx = dx * 0.5 + 0.5;
  70115. var px = Math.round(dx * inputWidth);
  70116. if (px < 0)
  70117. px = 0;
  70118. else if (px >= inputWidth)
  70119. px = inputWidth - 1;
  70120. var py = Math.round(dy * inputHeight);
  70121. if (py < 0)
  70122. py = 0;
  70123. else if (py >= inputHeight)
  70124. py = inputHeight - 1;
  70125. var inputY = (inputHeight - py - 1);
  70126. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  70127. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  70128. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  70129. return {
  70130. r: r,
  70131. g: g,
  70132. b: b
  70133. };
  70134. };
  70135. PanoramaToCubeMapTools.FACE_FRONT = [
  70136. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  70137. new BABYLON.Vector3(1.0, -1.0, -1.0),
  70138. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  70139. new BABYLON.Vector3(1.0, 1.0, -1.0)
  70140. ];
  70141. PanoramaToCubeMapTools.FACE_BACK = [
  70142. new BABYLON.Vector3(1.0, -1.0, 1.0),
  70143. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  70144. new BABYLON.Vector3(1.0, 1.0, 1.0),
  70145. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  70146. ];
  70147. PanoramaToCubeMapTools.FACE_RIGHT = [
  70148. new BABYLON.Vector3(1.0, -1.0, -1.0),
  70149. new BABYLON.Vector3(1.0, -1.0, 1.0),
  70150. new BABYLON.Vector3(1.0, 1.0, -1.0),
  70151. new BABYLON.Vector3(1.0, 1.0, 1.0)
  70152. ];
  70153. PanoramaToCubeMapTools.FACE_LEFT = [
  70154. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  70155. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  70156. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  70157. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  70158. ];
  70159. PanoramaToCubeMapTools.FACE_DOWN = [
  70160. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  70161. new BABYLON.Vector3(1.0, 1.0, -1.0),
  70162. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  70163. new BABYLON.Vector3(1.0, 1.0, 1.0)
  70164. ];
  70165. PanoramaToCubeMapTools.FACE_UP = [
  70166. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  70167. new BABYLON.Vector3(1.0, -1.0, 1.0),
  70168. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  70169. new BABYLON.Vector3(1.0, -1.0, -1.0)
  70170. ];
  70171. return PanoramaToCubeMapTools;
  70172. }());
  70173. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  70174. })(BABYLON || (BABYLON = {}));
  70175. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  70176. var BABYLON;
  70177. (function (BABYLON) {
  70178. ;
  70179. /**
  70180. * This groups tools to convert HDR texture to native colors array.
  70181. */
  70182. var HDRTools = /** @class */ (function () {
  70183. function HDRTools() {
  70184. }
  70185. HDRTools.Ldexp = function (mantissa, exponent) {
  70186. if (exponent > 1023) {
  70187. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  70188. }
  70189. if (exponent < -1074) {
  70190. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  70191. }
  70192. return mantissa * Math.pow(2, exponent);
  70193. };
  70194. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  70195. if (exponent > 0) {
  70196. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  70197. float32array[index + 0] = red * exponent;
  70198. float32array[index + 1] = green * exponent;
  70199. float32array[index + 2] = blue * exponent;
  70200. }
  70201. else {
  70202. float32array[index + 0] = 0;
  70203. float32array[index + 1] = 0;
  70204. float32array[index + 2] = 0;
  70205. }
  70206. };
  70207. HDRTools.readStringLine = function (uint8array, startIndex) {
  70208. var line = "";
  70209. var character = "";
  70210. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  70211. character = String.fromCharCode(uint8array[i]);
  70212. if (character == "\n") {
  70213. break;
  70214. }
  70215. line += character;
  70216. }
  70217. return line;
  70218. };
  70219. /**
  70220. * Reads header information from an RGBE texture stored in a native array.
  70221. * More information on this format are available here:
  70222. * https://en.wikipedia.org/wiki/RGBE_image_format
  70223. *
  70224. * @param uint8array The binary file stored in native array.
  70225. * @return The header information.
  70226. */
  70227. HDRTools.RGBE_ReadHeader = function (uint8array) {
  70228. var height = 0;
  70229. var width = 0;
  70230. var line = this.readStringLine(uint8array, 0);
  70231. if (line[0] != '#' || line[1] != '?') {
  70232. throw "Bad HDR Format.";
  70233. }
  70234. var endOfHeader = false;
  70235. var findFormat = false;
  70236. var lineIndex = 0;
  70237. do {
  70238. lineIndex += (line.length + 1);
  70239. line = this.readStringLine(uint8array, lineIndex);
  70240. if (line == "FORMAT=32-bit_rle_rgbe") {
  70241. findFormat = true;
  70242. }
  70243. else if (line.length == 0) {
  70244. endOfHeader = true;
  70245. }
  70246. } while (!endOfHeader);
  70247. if (!findFormat) {
  70248. throw "HDR Bad header format, unsupported FORMAT";
  70249. }
  70250. lineIndex += (line.length + 1);
  70251. line = this.readStringLine(uint8array, lineIndex);
  70252. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  70253. var match = sizeRegexp.exec(line);
  70254. // TODO. Support +Y and -X if needed.
  70255. if (!match || match.length < 3) {
  70256. throw "HDR Bad header format, no size";
  70257. }
  70258. width = parseInt(match[2]);
  70259. height = parseInt(match[1]);
  70260. if (width < 8 || width > 0x7fff) {
  70261. throw "HDR Bad header format, unsupported size";
  70262. }
  70263. lineIndex += (line.length + 1);
  70264. return {
  70265. height: height,
  70266. width: width,
  70267. dataPosition: lineIndex
  70268. };
  70269. };
  70270. /**
  70271. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  70272. * This RGBE texture needs to store the information as a panorama.
  70273. *
  70274. * More information on this format are available here:
  70275. * https://en.wikipedia.org/wiki/RGBE_image_format
  70276. *
  70277. * @param buffer The binary file stored in an array buffer.
  70278. * @param size The expected size of the extracted cubemap.
  70279. * @return The Cube Map information.
  70280. */
  70281. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  70282. var uint8array = new Uint8Array(buffer);
  70283. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  70284. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  70285. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  70286. return cubeMapData;
  70287. };
  70288. /**
  70289. * Returns the pixels data extracted from an RGBE texture.
  70290. * This pixels will be stored left to right up to down in the R G B order in one array.
  70291. *
  70292. * More information on this format are available here:
  70293. * https://en.wikipedia.org/wiki/RGBE_image_format
  70294. *
  70295. * @param uint8array The binary file stored in an array buffer.
  70296. * @param hdrInfo The header information of the file.
  70297. * @return The pixels data in RGB right to left up to down order.
  70298. */
  70299. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  70300. // Keep for multi format supports.
  70301. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  70302. };
  70303. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  70304. var num_scanlines = hdrInfo.height;
  70305. var scanline_width = hdrInfo.width;
  70306. var a, b, c, d, count;
  70307. var dataIndex = hdrInfo.dataPosition;
  70308. var index = 0, endIndex = 0, i = 0;
  70309. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  70310. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  70311. // 3 channels of 4 bytes per pixel in float.
  70312. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  70313. var resultArray = new Float32Array(resultBuffer);
  70314. // read in each successive scanline
  70315. while (num_scanlines > 0) {
  70316. a = uint8array[dataIndex++];
  70317. b = uint8array[dataIndex++];
  70318. c = uint8array[dataIndex++];
  70319. d = uint8array[dataIndex++];
  70320. if (a != 2 || b != 2 || (c & 0x80)) {
  70321. // this file is not run length encoded
  70322. throw "HDR Bad header format, not RLE";
  70323. }
  70324. if (((c << 8) | d) != scanline_width) {
  70325. throw "HDR Bad header format, wrong scan line width";
  70326. }
  70327. index = 0;
  70328. // read each of the four channels for the scanline into the buffer
  70329. for (i = 0; i < 4; i++) {
  70330. endIndex = (i + 1) * scanline_width;
  70331. while (index < endIndex) {
  70332. a = uint8array[dataIndex++];
  70333. b = uint8array[dataIndex++];
  70334. if (a > 128) {
  70335. // a run of the same value
  70336. count = a - 128;
  70337. if ((count == 0) || (count > endIndex - index)) {
  70338. throw "HDR Bad Format, bad scanline data (run)";
  70339. }
  70340. while (count-- > 0) {
  70341. scanLineArray[index++] = b;
  70342. }
  70343. }
  70344. else {
  70345. // a non-run
  70346. count = a;
  70347. if ((count == 0) || (count > endIndex - index)) {
  70348. throw "HDR Bad Format, bad scanline data (non-run)";
  70349. }
  70350. scanLineArray[index++] = b;
  70351. if (--count > 0) {
  70352. for (var j = 0; j < count; j++) {
  70353. scanLineArray[index++] = uint8array[dataIndex++];
  70354. }
  70355. }
  70356. }
  70357. }
  70358. }
  70359. // now convert data from buffer into floats
  70360. for (i = 0; i < scanline_width; i++) {
  70361. a = scanLineArray[i];
  70362. b = scanLineArray[i + scanline_width];
  70363. c = scanLineArray[i + 2 * scanline_width];
  70364. d = scanLineArray[i + 3 * scanline_width];
  70365. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  70366. }
  70367. num_scanlines--;
  70368. }
  70369. return resultArray;
  70370. };
  70371. return HDRTools;
  70372. }());
  70373. BABYLON.HDRTools = HDRTools;
  70374. })(BABYLON || (BABYLON = {}));
  70375. //# sourceMappingURL=babylon.hdr.js.map
  70376. var BABYLON;
  70377. (function (BABYLON) {
  70378. /**
  70379. * This represents a texture coming from an HDR input.
  70380. *
  70381. * The only supported format is currently panorama picture stored in RGBE format.
  70382. * Example of such files can be found on HDRLib: http://hdrlib.com/
  70383. */
  70384. var HDRCubeTexture = /** @class */ (function (_super) {
  70385. __extends(HDRCubeTexture, _super);
  70386. /**
  70387. * Instantiates an HDRTexture from the following parameters.
  70388. *
  70389. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  70390. * @param scene The scene the texture will be used in
  70391. * @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.
  70392. * @param noMipmap Forces to not generate the mipmap if true
  70393. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  70394. * @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)
  70395. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  70396. */
  70397. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  70398. if (noMipmap === void 0) { noMipmap = false; }
  70399. if (generateHarmonics === void 0) { generateHarmonics = true; }
  70400. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  70401. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  70402. if (onLoad === void 0) { onLoad = null; }
  70403. if (onError === void 0) { onError = null; }
  70404. var _this = _super.call(this, scene) || this;
  70405. _this._useInGammaSpace = false;
  70406. _this._generateHarmonics = true;
  70407. _this._isBABYLONPreprocessed = false;
  70408. _this._onLoad = null;
  70409. _this._onError = null;
  70410. /**
  70411. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  70412. */
  70413. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  70414. /**
  70415. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  70416. * This is usefull at run time to apply the good shader.
  70417. */
  70418. _this.isPMREM = false;
  70419. _this._isBlocking = true;
  70420. if (!url) {
  70421. return _this;
  70422. }
  70423. _this.name = url;
  70424. _this.url = url;
  70425. _this.hasAlpha = false;
  70426. _this.isCube = true;
  70427. _this._textureMatrix = BABYLON.Matrix.Identity();
  70428. _this._onLoad = onLoad;
  70429. _this._onError = onError;
  70430. _this.gammaSpace = false;
  70431. var caps = scene.getEngine().getCaps();
  70432. if (size) {
  70433. _this._isBABYLONPreprocessed = false;
  70434. _this._noMipmap = noMipmap;
  70435. _this._size = size;
  70436. _this._useInGammaSpace = useInGammaSpace;
  70437. _this._usePMREMGenerator = usePMREMGenerator &&
  70438. caps.textureLOD &&
  70439. caps.textureFloat &&
  70440. !_this._useInGammaSpace;
  70441. }
  70442. else {
  70443. _this._isBABYLONPreprocessed = true;
  70444. _this._noMipmap = false;
  70445. _this._useInGammaSpace = false;
  70446. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  70447. !_this._useInGammaSpace;
  70448. }
  70449. _this.isPMREM = _this._usePMREMGenerator;
  70450. _this._texture = _this._getFromCache(url, _this._noMipmap);
  70451. if (!_this._texture) {
  70452. if (!scene.useDelayedTextureLoading) {
  70453. _this.loadTexture();
  70454. }
  70455. else {
  70456. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  70457. }
  70458. }
  70459. return _this;
  70460. }
  70461. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  70462. /**
  70463. * Gets wether or not the texture is blocking during loading.
  70464. */
  70465. get: function () {
  70466. return this._isBlocking;
  70467. },
  70468. /**
  70469. * Sets wether or not the texture is blocking during loading.
  70470. */
  70471. set: function (value) {
  70472. this._isBlocking = value;
  70473. },
  70474. enumerable: true,
  70475. configurable: true
  70476. });
  70477. /**
  70478. * Occurs when the file is a preprocessed .babylon.hdr file.
  70479. */
  70480. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  70481. var _this = this;
  70482. var mipLevels = 0;
  70483. var floatArrayView = null;
  70484. var scene = this.getScene();
  70485. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  70486. var mips = new Array();
  70487. if (!floatArrayView) {
  70488. return mips;
  70489. }
  70490. var startIndex = 30;
  70491. for (var level = 0; level < mipLevels; level++) {
  70492. mips.push([]);
  70493. // Fill each pixel of the mip level.
  70494. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  70495. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  70496. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  70497. mips[level].push(faceData);
  70498. startIndex += faceSize;
  70499. }
  70500. }
  70501. return mips;
  70502. } : null;
  70503. var callback = function (buffer) {
  70504. var scene = _this.getScene();
  70505. if (!scene) {
  70506. return null;
  70507. }
  70508. // Create Native Array Views
  70509. var intArrayView = new Int32Array(buffer);
  70510. floatArrayView = new Float32Array(buffer);
  70511. // Fill header.
  70512. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  70513. _this._size = intArrayView[1]; // CubeMap max mip face size.
  70514. // Update Texture Information.
  70515. if (!_this._texture) {
  70516. return null;
  70517. }
  70518. _this._texture.updateSize(_this._size, _this._size);
  70519. // Fill polynomial information.
  70520. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  70521. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  70522. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  70523. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  70524. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  70525. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  70526. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  70527. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  70528. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  70529. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  70530. _this.sphericalPolynomial = sphericalPolynomial;
  70531. // Fill pixel data.
  70532. mipLevels = intArrayView[29]; // Number of mip levels.
  70533. var startIndex = 30;
  70534. var data = [];
  70535. var faceSize = Math.pow(_this._size, 2) * 3;
  70536. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  70537. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  70538. startIndex += faceSize;
  70539. }
  70540. var results = [];
  70541. var byteArray = null;
  70542. // Push each faces.
  70543. for (var k = 0; k < 6; k++) {
  70544. var dataFace = null;
  70545. // To be deprecated.
  70546. if (version === 1) {
  70547. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  70548. dataFace = data[j];
  70549. }
  70550. // If special cases.
  70551. if (!mipmapGenerator && dataFace) {
  70552. if (!scene.getEngine().getCaps().textureFloat) {
  70553. // 3 channels of 1 bytes per pixel in bytes.
  70554. var byteBuffer = new ArrayBuffer(faceSize);
  70555. byteArray = new Uint8Array(byteBuffer);
  70556. }
  70557. for (var i = 0; i < _this._size * _this._size; i++) {
  70558. // Put in gamma space if requested.
  70559. if (_this._useInGammaSpace) {
  70560. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  70561. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  70562. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  70563. }
  70564. // Convert to int texture for fallback.
  70565. if (byteArray) {
  70566. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  70567. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  70568. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  70569. // May use luminance instead if the result is not accurate.
  70570. var max = Math.max(Math.max(r, g), b);
  70571. if (max > 255) {
  70572. var scale = 255 / max;
  70573. r *= scale;
  70574. g *= scale;
  70575. b *= scale;
  70576. }
  70577. byteArray[(i * 3) + 0] = r;
  70578. byteArray[(i * 3) + 1] = g;
  70579. byteArray[(i * 3) + 2] = b;
  70580. }
  70581. }
  70582. }
  70583. // Fill the array accordingly.
  70584. if (byteArray) {
  70585. results.push(byteArray);
  70586. }
  70587. else {
  70588. results.push(dataFace);
  70589. }
  70590. }
  70591. return results;
  70592. };
  70593. if (scene) {
  70594. 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);
  70595. }
  70596. };
  70597. /**
  70598. * Occurs when the file is raw .hdr file.
  70599. */
  70600. HDRCubeTexture.prototype.loadHDRTexture = function () {
  70601. var _this = this;
  70602. var callback = function (buffer) {
  70603. var scene = _this.getScene();
  70604. if (!scene) {
  70605. return null;
  70606. }
  70607. // Extract the raw linear data.
  70608. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  70609. // Generate harmonics if needed.
  70610. if (_this._generateHarmonics) {
  70611. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  70612. _this.sphericalPolynomial = sphericalPolynomial;
  70613. }
  70614. var results = [];
  70615. var byteArray = null;
  70616. // Push each faces.
  70617. for (var j = 0; j < 6; j++) {
  70618. // Create uintarray fallback.
  70619. if (!scene.getEngine().getCaps().textureFloat) {
  70620. // 3 channels of 1 bytes per pixel in bytes.
  70621. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  70622. byteArray = new Uint8Array(byteBuffer);
  70623. }
  70624. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  70625. // If special cases.
  70626. if (_this._useInGammaSpace || byteArray) {
  70627. for (var i = 0; i < _this._size * _this._size; i++) {
  70628. // Put in gamma space if requested.
  70629. if (_this._useInGammaSpace) {
  70630. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  70631. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  70632. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  70633. }
  70634. // Convert to int texture for fallback.
  70635. if (byteArray) {
  70636. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  70637. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  70638. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  70639. // May use luminance instead if the result is not accurate.
  70640. var max = Math.max(Math.max(r, g), b);
  70641. if (max > 255) {
  70642. var scale = 255 / max;
  70643. r *= scale;
  70644. g *= scale;
  70645. b *= scale;
  70646. }
  70647. byteArray[(i * 3) + 0] = r;
  70648. byteArray[(i * 3) + 1] = g;
  70649. byteArray[(i * 3) + 2] = b;
  70650. }
  70651. }
  70652. }
  70653. if (byteArray) {
  70654. results.push(byteArray);
  70655. }
  70656. else {
  70657. results.push(dataFace);
  70658. }
  70659. }
  70660. return results;
  70661. };
  70662. var mipmapGenerator = null;
  70663. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  70664. // if (!this._noMipmap &&
  70665. // this._usePMREMGenerator) {
  70666. // mipmapGenerator = (data: ArrayBufferView[]) => {
  70667. // // Custom setup of the generator matching with the PBR shader values.
  70668. // var generator = new BABYLON.PMREMGenerator(data,
  70669. // this._size,
  70670. // this._size,
  70671. // 0,
  70672. // 3,
  70673. // this.getScene().getEngine().getCaps().textureFloat,
  70674. // 2048,
  70675. // 0.25,
  70676. // false,
  70677. // true);
  70678. // return generator.filterCubeMap();
  70679. // };
  70680. // }
  70681. var scene = this.getScene();
  70682. if (scene) {
  70683. 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);
  70684. }
  70685. };
  70686. /**
  70687. * Starts the loading process of the texture.
  70688. */
  70689. HDRCubeTexture.prototype.loadTexture = function () {
  70690. if (this._isBABYLONPreprocessed) {
  70691. this.loadBabylonTexture();
  70692. }
  70693. else {
  70694. this.loadHDRTexture();
  70695. }
  70696. };
  70697. HDRCubeTexture.prototype.clone = function () {
  70698. var scene = this.getScene();
  70699. if (!scene) {
  70700. return this;
  70701. }
  70702. var size = (this._isBABYLONPreprocessed ? null : this._size);
  70703. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  70704. // Base texture
  70705. newTexture.level = this.level;
  70706. newTexture.wrapU = this.wrapU;
  70707. newTexture.wrapV = this.wrapV;
  70708. newTexture.coordinatesIndex = this.coordinatesIndex;
  70709. newTexture.coordinatesMode = this.coordinatesMode;
  70710. return newTexture;
  70711. };
  70712. // Methods
  70713. HDRCubeTexture.prototype.delayLoad = function () {
  70714. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  70715. return;
  70716. }
  70717. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  70718. this._texture = this._getFromCache(this.url, this._noMipmap);
  70719. if (!this._texture) {
  70720. this.loadTexture();
  70721. }
  70722. };
  70723. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  70724. return this._textureMatrix;
  70725. };
  70726. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  70727. this._textureMatrix = value;
  70728. };
  70729. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  70730. var texture = null;
  70731. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  70732. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  70733. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  70734. texture.name = parsedTexture.name;
  70735. texture.hasAlpha = parsedTexture.hasAlpha;
  70736. texture.level = parsedTexture.level;
  70737. texture.coordinatesMode = parsedTexture.coordinatesMode;
  70738. texture.isBlocking = parsedTexture.isBlocking;
  70739. }
  70740. return texture;
  70741. };
  70742. HDRCubeTexture.prototype.serialize = function () {
  70743. if (!this.name) {
  70744. return null;
  70745. }
  70746. var serializationObject = {};
  70747. serializationObject.name = this.name;
  70748. serializationObject.hasAlpha = this.hasAlpha;
  70749. serializationObject.isCube = true;
  70750. serializationObject.level = this.level;
  70751. serializationObject.size = this._size;
  70752. serializationObject.coordinatesMode = this.coordinatesMode;
  70753. serializationObject.useInGammaSpace = this._useInGammaSpace;
  70754. serializationObject.generateHarmonics = this._generateHarmonics;
  70755. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  70756. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  70757. serializationObject.customType = "BABYLON.HDRCubeTexture";
  70758. serializationObject.noMipmap = this._noMipmap;
  70759. serializationObject.isBlocking = this._isBlocking;
  70760. return serializationObject;
  70761. };
  70762. /**
  70763. * Saves as a file the data contained in the texture in a binary format.
  70764. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  70765. * as the spherical used in the lighting.
  70766. * @param url The HDR file url.
  70767. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  70768. * @param onError Method called if any error happens during download.
  70769. * @return The packed binary data.
  70770. */
  70771. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  70772. if (onError === void 0) { onError = null; }
  70773. var callback = function (buffer) {
  70774. var data = new Blob([buffer], { type: 'application/octet-stream' });
  70775. // Returns a URL you can use as a href.
  70776. var objUrl = window.URL.createObjectURL(data);
  70777. // Simulates a link to it and click to dowload.
  70778. var a = document.createElement("a");
  70779. document.body.appendChild(a);
  70780. a.style.display = "none";
  70781. a.href = objUrl;
  70782. a.download = "envmap.babylon.hdr";
  70783. a.click();
  70784. };
  70785. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  70786. };
  70787. /**
  70788. * Serializes the data contained in the texture in a binary format.
  70789. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  70790. * as the spherical used in the lighting.
  70791. * @param url The HDR file url.
  70792. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  70793. * @param onError Method called if any error happens during download.
  70794. * @return The packed binary data.
  70795. */
  70796. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  70797. if (onError === void 0) { onError = null; }
  70798. // Needs the url tho create the texture.
  70799. if (!url) {
  70800. return;
  70801. }
  70802. // Check Power of two size.
  70803. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  70804. return;
  70805. }
  70806. // Coming Back in 3.x.
  70807. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  70808. };
  70809. HDRCubeTexture._facesMapping = [
  70810. "right",
  70811. "left",
  70812. "up",
  70813. "down",
  70814. "front",
  70815. "back"
  70816. ];
  70817. return HDRCubeTexture;
  70818. }(BABYLON.BaseTexture));
  70819. BABYLON.HDRCubeTexture = HDRCubeTexture;
  70820. })(BABYLON || (BABYLON = {}));
  70821. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  70822. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  70823. // Huge respect for a such great lib.
  70824. // Earcut license:
  70825. // Copyright (c) 2016, Mapbox
  70826. //
  70827. // Permission to use, copy, modify, and/or distribute this software for any purpose
  70828. // with or without fee is hereby granted, provided that the above copyright notice
  70829. // and this permission notice appear in all copies.
  70830. //
  70831. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  70832. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  70833. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  70834. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  70835. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  70836. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  70837. // THIS SOFTWARE.
  70838. var Earcut;
  70839. (function (Earcut) {
  70840. /**
  70841. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  70842. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  70843. * @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).
  70844. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  70845. */
  70846. function earcut(data, holeIndices, dim) {
  70847. dim = dim || 2;
  70848. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  70849. if (!outerNode)
  70850. return triangles;
  70851. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  70852. if (hasHoles)
  70853. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  70854. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  70855. if (data.length > 80 * dim) {
  70856. minX = maxX = data[0];
  70857. minY = maxY = data[1];
  70858. for (var i = dim; i < outerLen; i += dim) {
  70859. x = data[i];
  70860. y = data[i + 1];
  70861. if (x < minX)
  70862. minX = x;
  70863. if (y < minY)
  70864. minY = y;
  70865. if (x > maxX)
  70866. maxX = x;
  70867. if (y > maxY)
  70868. maxY = y;
  70869. }
  70870. // minX, minY and size are later used to transform coords into integers for z-order calculation
  70871. size = Math.max(maxX - minX, maxY - minY);
  70872. }
  70873. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  70874. return triangles;
  70875. }
  70876. Earcut.earcut = earcut;
  70877. var Node = /** @class */ (function () {
  70878. function Node(i, x, y) {
  70879. this.i = i;
  70880. this.x = x;
  70881. this.y = y;
  70882. this.prev = null;
  70883. this.next = null;
  70884. this.z = null;
  70885. this.prevZ = null;
  70886. this.nextZ = null;
  70887. this.steiner = false;
  70888. }
  70889. return Node;
  70890. }());
  70891. // create a circular doubly linked list from polygon points in the specified winding order
  70892. function linkedList(data, start, end, dim, clockwise) {
  70893. var i, last = null;
  70894. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  70895. for (i = start; i < end; i += dim)
  70896. last = insertNode(i, data[i], data[i + 1], last);
  70897. }
  70898. else {
  70899. for (i = end - dim; i >= start; i -= dim)
  70900. last = insertNode(i, data[i], data[i + 1], last);
  70901. }
  70902. if (last && equals(last, last.next)) {
  70903. removeNode(last);
  70904. last = last.next;
  70905. }
  70906. return last;
  70907. }
  70908. // eliminate colinear or duplicate points
  70909. function filterPoints(start, end) {
  70910. if (!start)
  70911. return start;
  70912. if (!end)
  70913. end = start;
  70914. var p = start, again;
  70915. do {
  70916. again = false;
  70917. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  70918. removeNode(p);
  70919. p = end = p.prev;
  70920. if (p === p.next)
  70921. return undefined;
  70922. again = true;
  70923. }
  70924. else {
  70925. p = p.next;
  70926. }
  70927. } while (again || p !== end);
  70928. return end;
  70929. }
  70930. // main ear slicing loop which triangulates a polygon (given as a linked list)
  70931. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  70932. if (!ear)
  70933. return;
  70934. // interlink polygon nodes in z-order
  70935. if (!pass && size)
  70936. indexCurve(ear, minX, minY, size);
  70937. var stop = ear, prev, next;
  70938. // iterate through ears, slicing them one by one
  70939. while (ear.prev !== ear.next) {
  70940. prev = ear.prev;
  70941. next = ear.next;
  70942. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  70943. // cut off the triangle
  70944. triangles.push(prev.i / dim);
  70945. triangles.push(ear.i / dim);
  70946. triangles.push(next.i / dim);
  70947. removeNode(ear);
  70948. // skipping the next vertice leads to less sliver triangles
  70949. ear = next.next;
  70950. stop = next.next;
  70951. continue;
  70952. }
  70953. ear = next;
  70954. // if we looped through the whole remaining polygon and can't find any more ears
  70955. if (ear === stop) {
  70956. // try filtering points and slicing again
  70957. if (!pass) {
  70958. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  70959. // if this didn't work, try curing all small self-intersections locally
  70960. }
  70961. else if (pass === 1) {
  70962. ear = cureLocalIntersections(ear, triangles, dim);
  70963. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  70964. // as a last resort, try splitting the remaining polygon into two
  70965. }
  70966. else if (pass === 2) {
  70967. splitEarcut(ear, triangles, dim, minX, minY, size);
  70968. }
  70969. break;
  70970. }
  70971. }
  70972. }
  70973. // check whether a polygon node forms a valid ear with adjacent nodes
  70974. function isEar(ear) {
  70975. var a = ear.prev, b = ear, c = ear.next;
  70976. if (area(a, b, c) >= 0)
  70977. return false; // reflex, can't be an ear
  70978. // now make sure we don't have other points inside the potential ear
  70979. var p = ear.next.next;
  70980. while (p !== ear.prev) {
  70981. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  70982. area(p.prev, p, p.next) >= 0)
  70983. return false;
  70984. p = p.next;
  70985. }
  70986. return true;
  70987. }
  70988. function isEarHashed(ear, minX, minY, size) {
  70989. var a = ear.prev, b = ear, c = ear.next;
  70990. if (area(a, b, c) >= 0)
  70991. return false; // reflex, can't be an ear
  70992. // triangle bbox; min & max are calculated like this for speed
  70993. 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);
  70994. // z-order range for the current triangle bbox;
  70995. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  70996. // first look for points inside the triangle in increasing z-order
  70997. var p = ear.nextZ;
  70998. while (p && p.z <= maxZ) {
  70999. if (p !== ear.prev &&
  71000. p !== ear.next &&
  71001. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71002. area(p.prev, p, p.next) >= 0)
  71003. return false;
  71004. p = p.nextZ;
  71005. }
  71006. // then look for points in decreasing z-order
  71007. p = ear.prevZ;
  71008. while (p && p.z >= minZ) {
  71009. if (p !== ear.prev &&
  71010. p !== ear.next &&
  71011. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71012. area(p.prev, p, p.next) >= 0)
  71013. return false;
  71014. p = p.prevZ;
  71015. }
  71016. return true;
  71017. }
  71018. // go through all polygon nodes and cure small local self-intersections
  71019. function cureLocalIntersections(start, triangles, dim) {
  71020. var p = start;
  71021. do {
  71022. var a = p.prev, b = p.next.next;
  71023. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  71024. triangles.push(a.i / dim);
  71025. triangles.push(p.i / dim);
  71026. triangles.push(b.i / dim);
  71027. // remove two nodes involved
  71028. removeNode(p);
  71029. removeNode(p.next);
  71030. p = start = b;
  71031. }
  71032. p = p.next;
  71033. } while (p !== start);
  71034. return p;
  71035. }
  71036. // try splitting polygon into two and triangulate them independently
  71037. function splitEarcut(start, triangles, dim, minX, minY, size) {
  71038. // look for a valid diagonal that divides the polygon into two
  71039. var a = start;
  71040. do {
  71041. var b = a.next.next;
  71042. while (b !== a.prev) {
  71043. if (a.i !== b.i && isValidDiagonal(a, b)) {
  71044. // split the polygon in two by the diagonal
  71045. var c = splitPolygon(a, b);
  71046. // filter colinear points around the cuts
  71047. a = filterPoints(a, a.next);
  71048. c = filterPoints(c, c.next);
  71049. // run earcut on each half
  71050. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  71051. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  71052. return;
  71053. }
  71054. b = b.next;
  71055. }
  71056. a = a.next;
  71057. } while (a !== start);
  71058. }
  71059. // link every hole into the outer loop, producing a single-ring polygon without holes
  71060. function eliminateHoles(data, holeIndices, outerNode, dim) {
  71061. var queue = [], i, len, start, end, list;
  71062. for (i = 0, len = holeIndices.length; i < len; i++) {
  71063. start = holeIndices[i] * dim;
  71064. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  71065. list = linkedList(data, start, end, dim, false);
  71066. if (list === list.next)
  71067. list.steiner = true;
  71068. queue.push(getLeftmost(list));
  71069. }
  71070. queue.sort(compareX);
  71071. // process holes from left to right
  71072. for (i = 0; i < queue.length; i++) {
  71073. eliminateHole(queue[i], outerNode);
  71074. outerNode = filterPoints(outerNode, outerNode.next);
  71075. }
  71076. return outerNode;
  71077. }
  71078. function compareX(a, b) {
  71079. return a.x - b.x;
  71080. }
  71081. // find a bridge between vertices that connects hole with an outer ring and and link it
  71082. function eliminateHole(hole, outerNode) {
  71083. outerNode = findHoleBridge(hole, outerNode);
  71084. if (outerNode) {
  71085. var b = splitPolygon(outerNode, hole);
  71086. filterPoints(b, b.next);
  71087. }
  71088. }
  71089. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  71090. function findHoleBridge(hole, outerNode) {
  71091. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  71092. // find a segment intersected by a ray from the hole's leftmost point to the left;
  71093. // segment's endpoint with lesser x will be potential connection point
  71094. do {
  71095. if (hy <= p.y && hy >= p.next.y) {
  71096. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  71097. if (x <= hx && x > qx) {
  71098. qx = x;
  71099. if (x === hx) {
  71100. if (hy === p.y)
  71101. return p;
  71102. if (hy === p.next.y)
  71103. return p.next;
  71104. }
  71105. m = p.x < p.next.x ? p : p.next;
  71106. }
  71107. }
  71108. p = p.next;
  71109. } while (p !== outerNode);
  71110. if (!m)
  71111. return null;
  71112. if (hx === qx)
  71113. return m.prev; // hole touches outer segment; pick lower endpoint
  71114. // look for points inside the triangle of hole point, segment intersection and endpoint;
  71115. // if there are no points found, we have a valid connection;
  71116. // otherwise choose the point of the minimum angle with the ray as connection point
  71117. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  71118. p = m.next;
  71119. while (p !== stop) {
  71120. if (hx >= p.x &&
  71121. p.x >= mx &&
  71122. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  71123. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  71124. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  71125. m = p;
  71126. tanMin = tan;
  71127. }
  71128. }
  71129. p = p.next;
  71130. }
  71131. return m;
  71132. }
  71133. // interlink polygon nodes in z-order
  71134. function indexCurve(start, minX, minY, size) {
  71135. var p = start;
  71136. do {
  71137. if (p.z === null)
  71138. p.z = zOrder(p.x, p.y, minX, minY, size);
  71139. p.prevZ = p.prev;
  71140. p.nextZ = p.next;
  71141. p = p.next;
  71142. } while (p !== start);
  71143. p.prevZ.nextZ = null;
  71144. p.prevZ = null;
  71145. sortLinked(p);
  71146. }
  71147. // Simon Tatham's linked list merge sort algorithm
  71148. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  71149. function sortLinked(list) {
  71150. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  71151. do {
  71152. p = list;
  71153. list = null;
  71154. tail = null;
  71155. numMerges = 0;
  71156. while (p) {
  71157. numMerges++;
  71158. q = p;
  71159. pSize = 0;
  71160. for (i = 0; i < inSize; i++) {
  71161. pSize++;
  71162. q = q.nextZ;
  71163. if (!q)
  71164. break;
  71165. }
  71166. qSize = inSize;
  71167. while (pSize > 0 || (qSize > 0 && q)) {
  71168. if (pSize === 0) {
  71169. e = q;
  71170. q = q.nextZ;
  71171. qSize--;
  71172. }
  71173. else if (qSize === 0 || !q) {
  71174. e = p;
  71175. p = p.nextZ;
  71176. pSize--;
  71177. }
  71178. else if (p.z <= q.z) {
  71179. e = p;
  71180. p = p.nextZ;
  71181. pSize--;
  71182. }
  71183. else {
  71184. e = q;
  71185. q = q.nextZ;
  71186. qSize--;
  71187. }
  71188. if (tail)
  71189. tail.nextZ = e;
  71190. else
  71191. list = e;
  71192. e.prevZ = tail;
  71193. tail = e;
  71194. }
  71195. p = q;
  71196. }
  71197. tail.nextZ = null;
  71198. inSize *= 2;
  71199. } while (numMerges > 1);
  71200. return list;
  71201. }
  71202. // z-order of a point given coords and size of the data bounding box
  71203. function zOrder(x, y, minX, minY, size) {
  71204. // coords are transformed into non-negative 15-bit integer range
  71205. x = 32767 * (x - minX) / size;
  71206. y = 32767 * (y - minY) / size;
  71207. x = (x | (x << 8)) & 0x00FF00FF;
  71208. x = (x | (x << 4)) & 0x0F0F0F0F;
  71209. x = (x | (x << 2)) & 0x33333333;
  71210. x = (x | (x << 1)) & 0x55555555;
  71211. y = (y | (y << 8)) & 0x00FF00FF;
  71212. y = (y | (y << 4)) & 0x0F0F0F0F;
  71213. y = (y | (y << 2)) & 0x33333333;
  71214. y = (y | (y << 1)) & 0x55555555;
  71215. return x | (y << 1);
  71216. }
  71217. // find the leftmost node of a polygon ring
  71218. function getLeftmost(start) {
  71219. var p = start, leftmost = start;
  71220. do {
  71221. if (p.x < leftmost.x)
  71222. leftmost = p;
  71223. p = p.next;
  71224. } while (p !== start);
  71225. return leftmost;
  71226. }
  71227. // check if a point lies within a convex triangle
  71228. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  71229. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  71230. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  71231. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  71232. }
  71233. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  71234. function isValidDiagonal(a, b) {
  71235. return a.next.i !== b.i &&
  71236. a.prev.i !== b.i &&
  71237. !intersectsPolygon(a, b) &&
  71238. locallyInside(a, b) &&
  71239. locallyInside(b, a) &&
  71240. middleInside(a, b);
  71241. }
  71242. // signed area of a triangle
  71243. function area(p, q, r) {
  71244. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  71245. }
  71246. // check if two points are equal
  71247. function equals(p1, p2) {
  71248. return p1.x === p2.x && p1.y === p2.y;
  71249. }
  71250. // check if two segments intersect
  71251. function intersects(p1, q1, p2, q2) {
  71252. if ((equals(p1, q1) && equals(p2, q2)) ||
  71253. (equals(p1, q2) && equals(p2, q1)))
  71254. return true;
  71255. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  71256. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  71257. }
  71258. // check if a polygon diagonal intersects any polygon segments
  71259. function intersectsPolygon(a, b) {
  71260. var p = a;
  71261. do {
  71262. if (p.i !== a.i &&
  71263. p.next.i !== a.i &&
  71264. p.i !== b.i &&
  71265. p.next.i !== b.i &&
  71266. intersects(p, p.next, a, b))
  71267. return true;
  71268. p = p.next;
  71269. } while (p !== a);
  71270. return false;
  71271. }
  71272. // check if a polygon diagonal is locally inside the polygon
  71273. function locallyInside(a, b) {
  71274. return area(a.prev, a, a.next) < 0
  71275. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  71276. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  71277. }
  71278. // check if the middle point of a polygon diagonal is inside the polygon
  71279. function middleInside(a, b) {
  71280. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  71281. do {
  71282. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  71283. inside = !inside;
  71284. p = p.next;
  71285. } while (p !== a);
  71286. return inside;
  71287. }
  71288. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  71289. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  71290. function splitPolygon(a, b) {
  71291. 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;
  71292. a.next = b;
  71293. b.prev = a;
  71294. a2.next = an;
  71295. an.prev = a2;
  71296. b2.next = a2;
  71297. a2.prev = b2;
  71298. bp.next = b2;
  71299. b2.prev = bp;
  71300. return b2;
  71301. }
  71302. // create a node and optionally link it with previous one (in a circular doubly linked list)
  71303. function insertNode(i, x, y, last) {
  71304. var p = new Node(i, x, y);
  71305. if (!last) {
  71306. p.prev = p;
  71307. p.next = p;
  71308. }
  71309. else {
  71310. p.next = last.next;
  71311. p.prev = last;
  71312. last.next.prev = p;
  71313. last.next = p;
  71314. }
  71315. return p;
  71316. }
  71317. function removeNode(p) {
  71318. p.next.prev = p.prev;
  71319. p.prev.next = p.next;
  71320. if (p.prevZ)
  71321. p.prevZ.nextZ = p.nextZ;
  71322. if (p.nextZ)
  71323. p.nextZ.prevZ = p.prevZ;
  71324. }
  71325. /**
  71326. * return a percentage difference between the polygon area and its triangulation area;
  71327. * used to verify correctness of triangulation
  71328. */
  71329. function deviation(data, holeIndices, dim, triangles) {
  71330. var hasHoles = holeIndices && holeIndices.length;
  71331. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  71332. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  71333. if (hasHoles) {
  71334. for (var i = 0, len = holeIndices.length; i < len; i++) {
  71335. var start = holeIndices[i] * dim;
  71336. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  71337. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  71338. }
  71339. }
  71340. var trianglesArea = 0;
  71341. for (i = 0; i < triangles.length; i += 3) {
  71342. var a = triangles[i] * dim;
  71343. var b = triangles[i + 1] * dim;
  71344. var c = triangles[i + 2] * dim;
  71345. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  71346. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  71347. }
  71348. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  71349. }
  71350. Earcut.deviation = deviation;
  71351. ;
  71352. function signedArea(data, start, end, dim) {
  71353. var sum = 0;
  71354. for (var i = start, j = end - dim; i < end; i += dim) {
  71355. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  71356. j = i;
  71357. }
  71358. return sum;
  71359. }
  71360. /**
  71361. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  71362. */
  71363. function flatten(data) {
  71364. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  71365. for (var i = 0; i < data.length; i++) {
  71366. for (var j = 0; j < data[i].length; j++) {
  71367. for (var d = 0; d < dim; d++)
  71368. result.vertices.push(data[i][j][d]);
  71369. }
  71370. if (i > 0) {
  71371. holeIndex += data[i - 1].length;
  71372. result.holes.push(holeIndex);
  71373. }
  71374. }
  71375. return result;
  71376. }
  71377. Earcut.flatten = flatten;
  71378. ;
  71379. })(Earcut || (Earcut = {}));
  71380. //# sourceMappingURL=babylon.earcut.js.map
  71381. var BABYLON;
  71382. (function (BABYLON) {
  71383. var IndexedVector2 = /** @class */ (function (_super) {
  71384. __extends(IndexedVector2, _super);
  71385. function IndexedVector2(original, index) {
  71386. var _this = _super.call(this, original.x, original.y) || this;
  71387. _this.index = index;
  71388. return _this;
  71389. }
  71390. return IndexedVector2;
  71391. }(BABYLON.Vector2));
  71392. var PolygonPoints = /** @class */ (function () {
  71393. function PolygonPoints() {
  71394. this.elements = new Array();
  71395. }
  71396. PolygonPoints.prototype.add = function (originalPoints) {
  71397. var _this = this;
  71398. var result = new Array();
  71399. originalPoints.forEach(function (point) {
  71400. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  71401. var newPoint = new IndexedVector2(point, _this.elements.length);
  71402. result.push(newPoint);
  71403. _this.elements.push(newPoint);
  71404. }
  71405. });
  71406. return result;
  71407. };
  71408. PolygonPoints.prototype.computeBounds = function () {
  71409. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  71410. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  71411. this.elements.forEach(function (point) {
  71412. // x
  71413. if (point.x < lmin.x) {
  71414. lmin.x = point.x;
  71415. }
  71416. else if (point.x > lmax.x) {
  71417. lmax.x = point.x;
  71418. }
  71419. // y
  71420. if (point.y < lmin.y) {
  71421. lmin.y = point.y;
  71422. }
  71423. else if (point.y > lmax.y) {
  71424. lmax.y = point.y;
  71425. }
  71426. });
  71427. return {
  71428. min: lmin,
  71429. max: lmax,
  71430. width: lmax.x - lmin.x,
  71431. height: lmax.y - lmin.y
  71432. };
  71433. };
  71434. return PolygonPoints;
  71435. }());
  71436. var Polygon = /** @class */ (function () {
  71437. function Polygon() {
  71438. }
  71439. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  71440. return [
  71441. new BABYLON.Vector2(xmin, ymin),
  71442. new BABYLON.Vector2(xmax, ymin),
  71443. new BABYLON.Vector2(xmax, ymax),
  71444. new BABYLON.Vector2(xmin, ymax)
  71445. ];
  71446. };
  71447. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  71448. if (cx === void 0) { cx = 0; }
  71449. if (cy === void 0) { cy = 0; }
  71450. if (numberOfSides === void 0) { numberOfSides = 32; }
  71451. var result = new Array();
  71452. var angle = 0;
  71453. var increment = (Math.PI * 2) / numberOfSides;
  71454. for (var i = 0; i < numberOfSides; i++) {
  71455. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  71456. angle -= increment;
  71457. }
  71458. return result;
  71459. };
  71460. Polygon.Parse = function (input) {
  71461. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  71462. var i, result = [];
  71463. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  71464. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  71465. }
  71466. return result;
  71467. };
  71468. Polygon.StartingAt = function (x, y) {
  71469. return BABYLON.Path2.StartingAt(x, y);
  71470. };
  71471. return Polygon;
  71472. }());
  71473. BABYLON.Polygon = Polygon;
  71474. var PolygonMeshBuilder = /** @class */ (function () {
  71475. function PolygonMeshBuilder(name, contours, scene) {
  71476. this._points = new PolygonPoints();
  71477. this._outlinepoints = new PolygonPoints();
  71478. this._holes = new Array();
  71479. this._epoints = new Array();
  71480. this._eholes = new Array();
  71481. this._name = name;
  71482. this._scene = scene;
  71483. var points;
  71484. if (contours instanceof BABYLON.Path2) {
  71485. points = contours.getPoints();
  71486. }
  71487. else {
  71488. points = contours;
  71489. }
  71490. this._addToepoint(points);
  71491. this._points.add(points);
  71492. this._outlinepoints.add(points);
  71493. }
  71494. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  71495. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  71496. var p = points_1[_i];
  71497. this._epoints.push(p.x, p.y);
  71498. }
  71499. };
  71500. PolygonMeshBuilder.prototype.addHole = function (hole) {
  71501. this._points.add(hole);
  71502. var holepoints = new PolygonPoints();
  71503. holepoints.add(hole);
  71504. this._holes.push(holepoints);
  71505. this._eholes.push(this._epoints.length / 2);
  71506. this._addToepoint(hole);
  71507. return this;
  71508. };
  71509. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  71510. var _this = this;
  71511. if (updatable === void 0) { updatable = false; }
  71512. if (depth === void 0) { depth = 0; }
  71513. var result = new BABYLON.Mesh(this._name, this._scene);
  71514. var normals = new Array();
  71515. var positions = new Array();
  71516. var uvs = new Array();
  71517. var bounds = this._points.computeBounds();
  71518. this._points.elements.forEach(function (p) {
  71519. normals.push(0, 1.0, 0);
  71520. positions.push(p.x, 0, p.y);
  71521. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  71522. });
  71523. var indices = new Array();
  71524. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  71525. for (var i = 0; i < res.length; i++) {
  71526. indices.push(res[i]);
  71527. }
  71528. if (depth > 0) {
  71529. var positionscount = (positions.length / 3); //get the current pointcount
  71530. this._points.elements.forEach(function (p) {
  71531. normals.push(0, -1.0, 0);
  71532. positions.push(p.x, -depth, p.y);
  71533. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  71534. });
  71535. var totalCount = indices.length;
  71536. for (var i = 0; i < totalCount; i += 3) {
  71537. var i0 = indices[i + 0];
  71538. var i1 = indices[i + 1];
  71539. var i2 = indices[i + 2];
  71540. indices.push(i2 + positionscount);
  71541. indices.push(i1 + positionscount);
  71542. indices.push(i0 + positionscount);
  71543. }
  71544. //Add the sides
  71545. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  71546. this._holes.forEach(function (hole) {
  71547. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  71548. });
  71549. }
  71550. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  71551. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  71552. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  71553. result.setIndices(indices);
  71554. return result;
  71555. };
  71556. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  71557. var StartIndex = positions.length / 3;
  71558. var ulength = 0;
  71559. for (var i = 0; i < points.elements.length; i++) {
  71560. var p = points.elements[i];
  71561. var p1;
  71562. if ((i + 1) > points.elements.length - 1) {
  71563. p1 = points.elements[0];
  71564. }
  71565. else {
  71566. p1 = points.elements[i + 1];
  71567. }
  71568. positions.push(p.x, 0, p.y);
  71569. positions.push(p.x, -depth, p.y);
  71570. positions.push(p1.x, 0, p1.y);
  71571. positions.push(p1.x, -depth, p1.y);
  71572. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  71573. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  71574. var v3 = v2.subtract(v1);
  71575. var v4 = new BABYLON.Vector3(0, 1, 0);
  71576. var vn = BABYLON.Vector3.Cross(v3, v4);
  71577. vn = vn.normalize();
  71578. uvs.push(ulength / bounds.width, 0);
  71579. uvs.push(ulength / bounds.width, 1);
  71580. ulength += v3.length();
  71581. uvs.push((ulength / bounds.width), 0);
  71582. uvs.push((ulength / bounds.width), 1);
  71583. if (!flip) {
  71584. normals.push(-vn.x, -vn.y, -vn.z);
  71585. normals.push(-vn.x, -vn.y, -vn.z);
  71586. normals.push(-vn.x, -vn.y, -vn.z);
  71587. normals.push(-vn.x, -vn.y, -vn.z);
  71588. indices.push(StartIndex);
  71589. indices.push(StartIndex + 1);
  71590. indices.push(StartIndex + 2);
  71591. indices.push(StartIndex + 1);
  71592. indices.push(StartIndex + 3);
  71593. indices.push(StartIndex + 2);
  71594. }
  71595. else {
  71596. normals.push(vn.x, vn.y, vn.z);
  71597. normals.push(vn.x, vn.y, vn.z);
  71598. normals.push(vn.x, vn.y, vn.z);
  71599. normals.push(vn.x, vn.y, vn.z);
  71600. indices.push(StartIndex);
  71601. indices.push(StartIndex + 2);
  71602. indices.push(StartIndex + 1);
  71603. indices.push(StartIndex + 1);
  71604. indices.push(StartIndex + 2);
  71605. indices.push(StartIndex + 3);
  71606. }
  71607. StartIndex += 4;
  71608. }
  71609. ;
  71610. };
  71611. return PolygonMeshBuilder;
  71612. }());
  71613. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  71614. })(BABYLON || (BABYLON = {}));
  71615. //# sourceMappingURL=babylon.polygonMesh.js.map
  71616. var BABYLON;
  71617. (function (BABYLON) {
  71618. // Unique ID when we import meshes from Babylon to CSG
  71619. var currentCSGMeshId = 0;
  71620. // # class Vertex
  71621. // Represents a vertex of a polygon. Use your own vertex class instead of this
  71622. // one to provide additional features like texture coordinates and vertex
  71623. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  71624. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  71625. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  71626. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  71627. // is not used anywhere else.
  71628. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  71629. var Vertex = /** @class */ (function () {
  71630. function Vertex(pos, normal, uv) {
  71631. this.pos = pos;
  71632. this.normal = normal;
  71633. this.uv = uv;
  71634. }
  71635. Vertex.prototype.clone = function () {
  71636. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  71637. };
  71638. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  71639. // orientation of a polygon is flipped.
  71640. Vertex.prototype.flip = function () {
  71641. this.normal = this.normal.scale(-1);
  71642. };
  71643. // Create a new vertex between this vertex and `other` by linearly
  71644. // interpolating all properties using a parameter of `t`. Subclasses should
  71645. // override this to interpolate additional properties.
  71646. Vertex.prototype.interpolate = function (other, t) {
  71647. 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));
  71648. };
  71649. return Vertex;
  71650. }());
  71651. // # class Plane
  71652. // Represents a plane in 3D space.
  71653. var Plane = /** @class */ (function () {
  71654. function Plane(normal, w) {
  71655. this.normal = normal;
  71656. this.w = w;
  71657. }
  71658. Plane.FromPoints = function (a, b, c) {
  71659. var v0 = c.subtract(a);
  71660. var v1 = b.subtract(a);
  71661. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  71662. return null;
  71663. }
  71664. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  71665. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  71666. };
  71667. Plane.prototype.clone = function () {
  71668. return new Plane(this.normal.clone(), this.w);
  71669. };
  71670. Plane.prototype.flip = function () {
  71671. this.normal.scaleInPlace(-1);
  71672. this.w = -this.w;
  71673. };
  71674. // Split `polygon` by this plane if needed, then put the polygon or polygon
  71675. // fragments in the appropriate lists. Coplanar polygons go into either
  71676. // `coplanarFront` or `coplanarBack` depending on their orientation with
  71677. // respect to this plane. Polygons in front or in back of this plane go into
  71678. // either `front` or `back`.
  71679. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  71680. var COPLANAR = 0;
  71681. var FRONT = 1;
  71682. var BACK = 2;
  71683. var SPANNING = 3;
  71684. // Classify each point as well as the entire polygon into one of the above
  71685. // four classes.
  71686. var polygonType = 0;
  71687. var types = [];
  71688. var i;
  71689. var t;
  71690. for (i = 0; i < polygon.vertices.length; i++) {
  71691. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  71692. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  71693. polygonType |= type;
  71694. types.push(type);
  71695. }
  71696. // Put the polygon in the correct list, splitting it when necessary.
  71697. switch (polygonType) {
  71698. case COPLANAR:
  71699. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  71700. break;
  71701. case FRONT:
  71702. front.push(polygon);
  71703. break;
  71704. case BACK:
  71705. back.push(polygon);
  71706. break;
  71707. case SPANNING:
  71708. var f = [], b = [];
  71709. for (i = 0; i < polygon.vertices.length; i++) {
  71710. var j = (i + 1) % polygon.vertices.length;
  71711. var ti = types[i], tj = types[j];
  71712. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  71713. if (ti !== BACK)
  71714. f.push(vi);
  71715. if (ti !== FRONT)
  71716. b.push(ti !== BACK ? vi.clone() : vi);
  71717. if ((ti | tj) === SPANNING) {
  71718. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  71719. var v = vi.interpolate(vj, t);
  71720. f.push(v);
  71721. b.push(v.clone());
  71722. }
  71723. }
  71724. var poly;
  71725. if (f.length >= 3) {
  71726. poly = new Polygon(f, polygon.shared);
  71727. if (poly.plane)
  71728. front.push(poly);
  71729. }
  71730. if (b.length >= 3) {
  71731. poly = new Polygon(b, polygon.shared);
  71732. if (poly.plane)
  71733. back.push(poly);
  71734. }
  71735. break;
  71736. }
  71737. };
  71738. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  71739. // point is on the plane.
  71740. Plane.EPSILON = 1e-5;
  71741. return Plane;
  71742. }());
  71743. // # class Polygon
  71744. // Represents a convex polygon. The vertices used to initialize a polygon must
  71745. // be coplanar and form a convex loop.
  71746. //
  71747. // Each convex polygon has a `shared` property, which is shared between all
  71748. // polygons that are clones of each other or were split from the same polygon.
  71749. // This can be used to define per-polygon properties (such as surface color).
  71750. var Polygon = /** @class */ (function () {
  71751. function Polygon(vertices, shared) {
  71752. this.vertices = vertices;
  71753. this.shared = shared;
  71754. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  71755. }
  71756. Polygon.prototype.clone = function () {
  71757. var vertices = this.vertices.map(function (v) { return v.clone(); });
  71758. return new Polygon(vertices, this.shared);
  71759. };
  71760. Polygon.prototype.flip = function () {
  71761. this.vertices.reverse().map(function (v) { v.flip(); });
  71762. this.plane.flip();
  71763. };
  71764. return Polygon;
  71765. }());
  71766. // # class Node
  71767. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  71768. // by picking a polygon to split along. That polygon (and all other coplanar
  71769. // polygons) are added directly to that node and the other polygons are added to
  71770. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  71771. // no distinction between internal and leaf nodes.
  71772. var Node = /** @class */ (function () {
  71773. function Node(polygons) {
  71774. this.plane = null;
  71775. this.front = null;
  71776. this.back = null;
  71777. this.polygons = new Array();
  71778. if (polygons) {
  71779. this.build(polygons);
  71780. }
  71781. }
  71782. Node.prototype.clone = function () {
  71783. var node = new Node();
  71784. node.plane = this.plane && this.plane.clone();
  71785. node.front = this.front && this.front.clone();
  71786. node.back = this.back && this.back.clone();
  71787. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  71788. return node;
  71789. };
  71790. // Convert solid space to empty space and empty space to solid space.
  71791. Node.prototype.invert = function () {
  71792. for (var i = 0; i < this.polygons.length; i++) {
  71793. this.polygons[i].flip();
  71794. }
  71795. if (this.plane) {
  71796. this.plane.flip();
  71797. }
  71798. if (this.front) {
  71799. this.front.invert();
  71800. }
  71801. if (this.back) {
  71802. this.back.invert();
  71803. }
  71804. var temp = this.front;
  71805. this.front = this.back;
  71806. this.back = temp;
  71807. };
  71808. // Recursively remove all polygons in `polygons` that are inside this BSP
  71809. // tree.
  71810. Node.prototype.clipPolygons = function (polygons) {
  71811. if (!this.plane)
  71812. return polygons.slice();
  71813. var front = new Array(), back = new Array();
  71814. for (var i = 0; i < polygons.length; i++) {
  71815. this.plane.splitPolygon(polygons[i], front, back, front, back);
  71816. }
  71817. if (this.front) {
  71818. front = this.front.clipPolygons(front);
  71819. }
  71820. if (this.back) {
  71821. back = this.back.clipPolygons(back);
  71822. }
  71823. else {
  71824. back = [];
  71825. }
  71826. return front.concat(back);
  71827. };
  71828. // Remove all polygons in this BSP tree that are inside the other BSP tree
  71829. // `bsp`.
  71830. Node.prototype.clipTo = function (bsp) {
  71831. this.polygons = bsp.clipPolygons(this.polygons);
  71832. if (this.front)
  71833. this.front.clipTo(bsp);
  71834. if (this.back)
  71835. this.back.clipTo(bsp);
  71836. };
  71837. // Return a list of all polygons in this BSP tree.
  71838. Node.prototype.allPolygons = function () {
  71839. var polygons = this.polygons.slice();
  71840. if (this.front)
  71841. polygons = polygons.concat(this.front.allPolygons());
  71842. if (this.back)
  71843. polygons = polygons.concat(this.back.allPolygons());
  71844. return polygons;
  71845. };
  71846. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  71847. // new polygons are filtered down to the bottom of the tree and become new
  71848. // nodes there. Each set of polygons is partitioned using the first polygon
  71849. // (no heuristic is used to pick a good split).
  71850. Node.prototype.build = function (polygons) {
  71851. if (!polygons.length)
  71852. return;
  71853. if (!this.plane)
  71854. this.plane = polygons[0].plane.clone();
  71855. var front = new Array(), back = new Array();
  71856. for (var i = 0; i < polygons.length; i++) {
  71857. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  71858. }
  71859. if (front.length) {
  71860. if (!this.front)
  71861. this.front = new Node();
  71862. this.front.build(front);
  71863. }
  71864. if (back.length) {
  71865. if (!this.back)
  71866. this.back = new Node();
  71867. this.back.build(back);
  71868. }
  71869. };
  71870. return Node;
  71871. }());
  71872. var CSG = /** @class */ (function () {
  71873. function CSG() {
  71874. this.polygons = new Array();
  71875. }
  71876. // Convert BABYLON.Mesh to BABYLON.CSG
  71877. CSG.FromMesh = function (mesh) {
  71878. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  71879. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  71880. if (mesh instanceof BABYLON.Mesh) {
  71881. mesh.computeWorldMatrix(true);
  71882. matrix = mesh.getWorldMatrix();
  71883. meshPosition = mesh.position.clone();
  71884. meshRotation = mesh.rotation.clone();
  71885. if (mesh.rotationQuaternion) {
  71886. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  71887. }
  71888. meshScaling = mesh.scaling.clone();
  71889. }
  71890. else {
  71891. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  71892. }
  71893. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  71894. var subMeshes = mesh.subMeshes;
  71895. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  71896. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  71897. vertices = [];
  71898. for (var j = 0; j < 3; j++) {
  71899. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  71900. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  71901. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  71902. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  71903. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  71904. vertex = new Vertex(position, normal, uv);
  71905. vertices.push(vertex);
  71906. }
  71907. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  71908. // To handle the case of degenerated triangle
  71909. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  71910. if (polygon.plane)
  71911. polygons.push(polygon);
  71912. }
  71913. }
  71914. var csg = CSG.FromPolygons(polygons);
  71915. csg.matrix = matrix;
  71916. csg.position = meshPosition;
  71917. csg.rotation = meshRotation;
  71918. csg.scaling = meshScaling;
  71919. csg.rotationQuaternion = meshRotationQuaternion;
  71920. currentCSGMeshId++;
  71921. return csg;
  71922. };
  71923. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  71924. CSG.FromPolygons = function (polygons) {
  71925. var csg = new CSG();
  71926. csg.polygons = polygons;
  71927. return csg;
  71928. };
  71929. CSG.prototype.clone = function () {
  71930. var csg = new CSG();
  71931. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  71932. csg.copyTransformAttributes(this);
  71933. return csg;
  71934. };
  71935. CSG.prototype.union = function (csg) {
  71936. var a = new Node(this.clone().polygons);
  71937. var b = new Node(csg.clone().polygons);
  71938. a.clipTo(b);
  71939. b.clipTo(a);
  71940. b.invert();
  71941. b.clipTo(a);
  71942. b.invert();
  71943. a.build(b.allPolygons());
  71944. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  71945. };
  71946. CSG.prototype.unionInPlace = function (csg) {
  71947. var a = new Node(this.polygons);
  71948. var b = new Node(csg.polygons);
  71949. a.clipTo(b);
  71950. b.clipTo(a);
  71951. b.invert();
  71952. b.clipTo(a);
  71953. b.invert();
  71954. a.build(b.allPolygons());
  71955. this.polygons = a.allPolygons();
  71956. };
  71957. CSG.prototype.subtract = function (csg) {
  71958. var a = new Node(this.clone().polygons);
  71959. var b = new Node(csg.clone().polygons);
  71960. a.invert();
  71961. a.clipTo(b);
  71962. b.clipTo(a);
  71963. b.invert();
  71964. b.clipTo(a);
  71965. b.invert();
  71966. a.build(b.allPolygons());
  71967. a.invert();
  71968. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  71969. };
  71970. CSG.prototype.subtractInPlace = function (csg) {
  71971. var a = new Node(this.polygons);
  71972. var b = new Node(csg.polygons);
  71973. a.invert();
  71974. a.clipTo(b);
  71975. b.clipTo(a);
  71976. b.invert();
  71977. b.clipTo(a);
  71978. b.invert();
  71979. a.build(b.allPolygons());
  71980. a.invert();
  71981. this.polygons = a.allPolygons();
  71982. };
  71983. CSG.prototype.intersect = function (csg) {
  71984. var a = new Node(this.clone().polygons);
  71985. var b = new Node(csg.clone().polygons);
  71986. a.invert();
  71987. b.clipTo(a);
  71988. b.invert();
  71989. a.clipTo(b);
  71990. b.clipTo(a);
  71991. a.build(b.allPolygons());
  71992. a.invert();
  71993. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  71994. };
  71995. CSG.prototype.intersectInPlace = function (csg) {
  71996. var a = new Node(this.polygons);
  71997. var b = new Node(csg.polygons);
  71998. a.invert();
  71999. b.clipTo(a);
  72000. b.invert();
  72001. a.clipTo(b);
  72002. b.clipTo(a);
  72003. a.build(b.allPolygons());
  72004. a.invert();
  72005. this.polygons = a.allPolygons();
  72006. };
  72007. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  72008. // not modified.
  72009. CSG.prototype.inverse = function () {
  72010. var csg = this.clone();
  72011. csg.inverseInPlace();
  72012. return csg;
  72013. };
  72014. CSG.prototype.inverseInPlace = function () {
  72015. this.polygons.map(function (p) { p.flip(); });
  72016. };
  72017. // This is used to keep meshes transformations so they can be restored
  72018. // when we build back a Babylon Mesh
  72019. // NB : All CSG operations are performed in world coordinates
  72020. CSG.prototype.copyTransformAttributes = function (csg) {
  72021. this.matrix = csg.matrix;
  72022. this.position = csg.position;
  72023. this.rotation = csg.rotation;
  72024. this.scaling = csg.scaling;
  72025. this.rotationQuaternion = csg.rotationQuaternion;
  72026. return this;
  72027. };
  72028. // Build Raw mesh from CSG
  72029. // Coordinates here are in world space
  72030. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  72031. var matrix = this.matrix.clone();
  72032. matrix.invert();
  72033. 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;
  72034. if (keepSubMeshes) {
  72035. // Sort Polygons, since subMeshes are indices range
  72036. polygons.sort(function (a, b) {
  72037. if (a.shared.meshId === b.shared.meshId) {
  72038. return a.shared.subMeshId - b.shared.subMeshId;
  72039. }
  72040. else {
  72041. return a.shared.meshId - b.shared.meshId;
  72042. }
  72043. });
  72044. }
  72045. for (var i = 0, il = polygons.length; i < il; i++) {
  72046. polygon = polygons[i];
  72047. // Building SubMeshes
  72048. if (!subMesh_dict[polygon.shared.meshId]) {
  72049. subMesh_dict[polygon.shared.meshId] = {};
  72050. }
  72051. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  72052. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  72053. indexStart: +Infinity,
  72054. indexEnd: -Infinity,
  72055. materialIndex: polygon.shared.materialIndex
  72056. };
  72057. }
  72058. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  72059. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  72060. polygonIndices[0] = 0;
  72061. polygonIndices[1] = j - 1;
  72062. polygonIndices[2] = j;
  72063. for (var k = 0; k < 3; k++) {
  72064. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  72065. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  72066. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  72067. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  72068. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  72069. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  72070. // Check if 2 points can be merged
  72071. if (!(typeof vertex_idx !== 'undefined' &&
  72072. normals[vertex_idx * 3] === localNormal.x &&
  72073. normals[vertex_idx * 3 + 1] === localNormal.y &&
  72074. normals[vertex_idx * 3 + 2] === localNormal.z &&
  72075. uvs[vertex_idx * 2] === uv.x &&
  72076. uvs[vertex_idx * 2 + 1] === uv.y)) {
  72077. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  72078. uvs.push(uv.x, uv.y);
  72079. normals.push(normal.x, normal.y, normal.z);
  72080. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  72081. }
  72082. indices.push(vertex_idx);
  72083. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  72084. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  72085. currentIndex++;
  72086. }
  72087. }
  72088. }
  72089. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  72090. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  72091. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  72092. mesh.setIndices(indices, null);
  72093. if (keepSubMeshes) {
  72094. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  72095. var materialIndexOffset = 0, materialMaxIndex;
  72096. mesh.subMeshes = new Array();
  72097. for (var m in subMesh_dict) {
  72098. materialMaxIndex = -1;
  72099. for (var sm in subMesh_dict[m]) {
  72100. subMesh_obj = subMesh_dict[m][sm];
  72101. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  72102. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  72103. }
  72104. materialIndexOffset += ++materialMaxIndex;
  72105. }
  72106. }
  72107. return mesh;
  72108. };
  72109. // Build Mesh from CSG taking material and transforms into account
  72110. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  72111. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  72112. mesh.material = material;
  72113. mesh.position.copyFrom(this.position);
  72114. mesh.rotation.copyFrom(this.rotation);
  72115. if (this.rotationQuaternion) {
  72116. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  72117. }
  72118. mesh.scaling.copyFrom(this.scaling);
  72119. mesh.computeWorldMatrix(true);
  72120. return mesh;
  72121. };
  72122. return CSG;
  72123. }());
  72124. BABYLON.CSG = CSG;
  72125. })(BABYLON || (BABYLON = {}));
  72126. //# sourceMappingURL=babylon.csg.js.map
  72127. var BABYLON;
  72128. (function (BABYLON) {
  72129. var LensFlare = /** @class */ (function () {
  72130. function LensFlare(size, position, color, imgUrl, system) {
  72131. this.size = size;
  72132. this.position = position;
  72133. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  72134. this.color = color || new BABYLON.Color3(1, 1, 1);
  72135. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  72136. this._system = system;
  72137. system.lensFlares.push(this);
  72138. }
  72139. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  72140. return new LensFlare(size, position, color, imgUrl, system);
  72141. };
  72142. LensFlare.prototype.dispose = function () {
  72143. if (this.texture) {
  72144. this.texture.dispose();
  72145. }
  72146. // Remove from scene
  72147. var index = this._system.lensFlares.indexOf(this);
  72148. this._system.lensFlares.splice(index, 1);
  72149. };
  72150. ;
  72151. return LensFlare;
  72152. }());
  72153. BABYLON.LensFlare = LensFlare;
  72154. })(BABYLON || (BABYLON = {}));
  72155. //# sourceMappingURL=babylon.lensFlare.js.map
  72156. var BABYLON;
  72157. (function (BABYLON) {
  72158. var LensFlareSystem = /** @class */ (function () {
  72159. function LensFlareSystem(name, emitter, scene) {
  72160. this.name = name;
  72161. this.lensFlares = new Array();
  72162. this.borderLimit = 300;
  72163. this.viewportBorder = 0;
  72164. this.layerMask = 0x0FFFFFFF;
  72165. this._vertexBuffers = {};
  72166. this._isEnabled = true;
  72167. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72168. this._emitter = emitter;
  72169. this.id = name;
  72170. scene.lensFlareSystems.push(this);
  72171. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  72172. var engine = scene.getEngine();
  72173. // VBO
  72174. var vertices = [];
  72175. vertices.push(1, 1);
  72176. vertices.push(-1, 1);
  72177. vertices.push(-1, -1);
  72178. vertices.push(1, -1);
  72179. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  72180. // Indices
  72181. var indices = [];
  72182. indices.push(0);
  72183. indices.push(1);
  72184. indices.push(2);
  72185. indices.push(0);
  72186. indices.push(2);
  72187. indices.push(3);
  72188. this._indexBuffer = engine.createIndexBuffer(indices);
  72189. // Effects
  72190. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  72191. }
  72192. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  72193. get: function () {
  72194. return this._isEnabled;
  72195. },
  72196. set: function (value) {
  72197. this._isEnabled = value;
  72198. },
  72199. enumerable: true,
  72200. configurable: true
  72201. });
  72202. LensFlareSystem.prototype.getScene = function () {
  72203. return this._scene;
  72204. };
  72205. LensFlareSystem.prototype.getEmitter = function () {
  72206. return this._emitter;
  72207. };
  72208. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  72209. this._emitter = newEmitter;
  72210. };
  72211. LensFlareSystem.prototype.getEmitterPosition = function () {
  72212. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  72213. };
  72214. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  72215. var position = this.getEmitterPosition();
  72216. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  72217. this._positionX = position.x;
  72218. this._positionY = position.y;
  72219. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  72220. if (this.viewportBorder > 0) {
  72221. globalViewport.x -= this.viewportBorder;
  72222. globalViewport.y -= this.viewportBorder;
  72223. globalViewport.width += this.viewportBorder * 2;
  72224. globalViewport.height += this.viewportBorder * 2;
  72225. position.x += this.viewportBorder;
  72226. position.y += this.viewportBorder;
  72227. this._positionX += this.viewportBorder;
  72228. this._positionY += this.viewportBorder;
  72229. }
  72230. if (position.z > 0) {
  72231. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  72232. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  72233. return true;
  72234. }
  72235. return true;
  72236. }
  72237. return false;
  72238. };
  72239. LensFlareSystem.prototype._isVisible = function () {
  72240. if (!this._isEnabled || !this._scene.activeCamera) {
  72241. return false;
  72242. }
  72243. var emitterPosition = this.getEmitterPosition();
  72244. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  72245. var distance = direction.length();
  72246. direction.normalize();
  72247. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  72248. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  72249. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  72250. };
  72251. LensFlareSystem.prototype.render = function () {
  72252. if (!this._effect.isReady() || !this._scene.activeCamera)
  72253. return false;
  72254. var engine = this._scene.getEngine();
  72255. var viewport = this._scene.activeCamera.viewport;
  72256. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  72257. // Position
  72258. if (!this.computeEffectivePosition(globalViewport)) {
  72259. return false;
  72260. }
  72261. // Visibility
  72262. if (!this._isVisible()) {
  72263. return false;
  72264. }
  72265. // Intensity
  72266. var awayX;
  72267. var awayY;
  72268. if (this._positionX < this.borderLimit + globalViewport.x) {
  72269. awayX = this.borderLimit + globalViewport.x - this._positionX;
  72270. }
  72271. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  72272. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  72273. }
  72274. else {
  72275. awayX = 0;
  72276. }
  72277. if (this._positionY < this.borderLimit + globalViewport.y) {
  72278. awayY = this.borderLimit + globalViewport.y - this._positionY;
  72279. }
  72280. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  72281. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  72282. }
  72283. else {
  72284. awayY = 0;
  72285. }
  72286. var away = (awayX > awayY) ? awayX : awayY;
  72287. away -= this.viewportBorder;
  72288. if (away > this.borderLimit) {
  72289. away = this.borderLimit;
  72290. }
  72291. var intensity = 1.0 - (away / this.borderLimit);
  72292. if (intensity < 0) {
  72293. return false;
  72294. }
  72295. if (intensity > 1.0) {
  72296. intensity = 1.0;
  72297. }
  72298. if (this.viewportBorder > 0) {
  72299. globalViewport.x += this.viewportBorder;
  72300. globalViewport.y += this.viewportBorder;
  72301. globalViewport.width -= this.viewportBorder * 2;
  72302. globalViewport.height -= this.viewportBorder * 2;
  72303. this._positionX -= this.viewportBorder;
  72304. this._positionY -= this.viewportBorder;
  72305. }
  72306. // Position
  72307. var centerX = globalViewport.x + globalViewport.width / 2;
  72308. var centerY = globalViewport.y + globalViewport.height / 2;
  72309. var distX = centerX - this._positionX;
  72310. var distY = centerY - this._positionY;
  72311. // Effects
  72312. engine.enableEffect(this._effect);
  72313. engine.setState(false);
  72314. engine.setDepthBuffer(false);
  72315. // VBOs
  72316. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  72317. // Flares
  72318. for (var index = 0; index < this.lensFlares.length; index++) {
  72319. var flare = this.lensFlares[index];
  72320. engine.setAlphaMode(flare.alphaMode);
  72321. var x = centerX - (distX * flare.position);
  72322. var y = centerY - (distY * flare.position);
  72323. var cw = flare.size;
  72324. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  72325. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  72326. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  72327. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  72328. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  72329. // Texture
  72330. this._effect.setTexture("textureSampler", flare.texture);
  72331. // Color
  72332. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  72333. // Draw order
  72334. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  72335. }
  72336. engine.setDepthBuffer(true);
  72337. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  72338. return true;
  72339. };
  72340. LensFlareSystem.prototype.dispose = function () {
  72341. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72342. if (vertexBuffer) {
  72343. vertexBuffer.dispose();
  72344. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  72345. }
  72346. if (this._indexBuffer) {
  72347. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  72348. this._indexBuffer = null;
  72349. }
  72350. while (this.lensFlares.length) {
  72351. this.lensFlares[0].dispose();
  72352. }
  72353. // Remove from scene
  72354. var index = this._scene.lensFlareSystems.indexOf(this);
  72355. this._scene.lensFlareSystems.splice(index, 1);
  72356. };
  72357. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  72358. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  72359. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  72360. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  72361. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  72362. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  72363. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  72364. var parsedFlare = parsedLensFlareSystem.flares[index];
  72365. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  72366. }
  72367. return lensFlareSystem;
  72368. };
  72369. LensFlareSystem.prototype.serialize = function () {
  72370. var serializationObject = {};
  72371. serializationObject.id = this.id;
  72372. serializationObject.name = this.name;
  72373. serializationObject.emitterId = this.getEmitter().id;
  72374. serializationObject.borderLimit = this.borderLimit;
  72375. serializationObject.flares = [];
  72376. for (var index = 0; index < this.lensFlares.length; index++) {
  72377. var flare = this.lensFlares[index];
  72378. serializationObject.flares.push({
  72379. size: flare.size,
  72380. position: flare.position,
  72381. color: flare.color.asArray(),
  72382. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  72383. });
  72384. }
  72385. return serializationObject;
  72386. };
  72387. return LensFlareSystem;
  72388. }());
  72389. BABYLON.LensFlareSystem = LensFlareSystem;
  72390. })(BABYLON || (BABYLON = {}));
  72391. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  72392. var BABYLON;
  72393. (function (BABYLON) {
  72394. /**
  72395. * This is a holder class for the physics joint created by the physics plugin.
  72396. * It holds a set of functions to control the underlying joint.
  72397. */
  72398. var PhysicsJoint = /** @class */ (function () {
  72399. function PhysicsJoint(type, jointData) {
  72400. this.type = type;
  72401. this.jointData = jointData;
  72402. jointData.nativeParams = jointData.nativeParams || {};
  72403. }
  72404. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  72405. get: function () {
  72406. return this._physicsJoint;
  72407. },
  72408. set: function (newJoint) {
  72409. if (this._physicsJoint) {
  72410. //remove from the wolrd
  72411. }
  72412. this._physicsJoint = newJoint;
  72413. },
  72414. enumerable: true,
  72415. configurable: true
  72416. });
  72417. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  72418. set: function (physicsPlugin) {
  72419. this._physicsPlugin = physicsPlugin;
  72420. },
  72421. enumerable: true,
  72422. configurable: true
  72423. });
  72424. /**
  72425. * Execute a function that is physics-plugin specific.
  72426. * @param {Function} func the function that will be executed.
  72427. * It accepts two parameters: the physics world and the physics joint.
  72428. */
  72429. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  72430. func(this._physicsPlugin.world, this._physicsJoint);
  72431. };
  72432. //TODO check if the native joints are the same
  72433. //Joint Types
  72434. PhysicsJoint.DistanceJoint = 0;
  72435. PhysicsJoint.HingeJoint = 1;
  72436. PhysicsJoint.BallAndSocketJoint = 2;
  72437. PhysicsJoint.WheelJoint = 3;
  72438. PhysicsJoint.SliderJoint = 4;
  72439. //OIMO
  72440. PhysicsJoint.PrismaticJoint = 5;
  72441. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  72442. PhysicsJoint.UniversalJoint = 6;
  72443. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  72444. //Cannon
  72445. //Similar to a Ball-Joint. Different in params
  72446. PhysicsJoint.PointToPointJoint = 8;
  72447. //Cannon only at the moment
  72448. PhysicsJoint.SpringJoint = 9;
  72449. PhysicsJoint.LockJoint = 10;
  72450. return PhysicsJoint;
  72451. }());
  72452. BABYLON.PhysicsJoint = PhysicsJoint;
  72453. /**
  72454. * A class representing a physics distance joint.
  72455. */
  72456. var DistanceJoint = /** @class */ (function (_super) {
  72457. __extends(DistanceJoint, _super);
  72458. function DistanceJoint(jointData) {
  72459. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  72460. }
  72461. /**
  72462. * Update the predefined distance.
  72463. */
  72464. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  72465. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  72466. };
  72467. return DistanceJoint;
  72468. }(PhysicsJoint));
  72469. BABYLON.DistanceJoint = DistanceJoint;
  72470. var MotorEnabledJoint = /** @class */ (function (_super) {
  72471. __extends(MotorEnabledJoint, _super);
  72472. function MotorEnabledJoint(type, jointData) {
  72473. return _super.call(this, type, jointData) || this;
  72474. }
  72475. /**
  72476. * Set the motor values.
  72477. * Attention, this function is plugin specific. Engines won't react 100% the same.
  72478. * @param {number} force the force to apply
  72479. * @param {number} maxForce max force for this motor.
  72480. */
  72481. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  72482. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  72483. };
  72484. /**
  72485. * Set the motor's limits.
  72486. * Attention, this function is plugin specific. Engines won't react 100% the same.
  72487. */
  72488. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  72489. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  72490. };
  72491. return MotorEnabledJoint;
  72492. }(PhysicsJoint));
  72493. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  72494. /**
  72495. * This class represents a single hinge physics joint
  72496. */
  72497. var HingeJoint = /** @class */ (function (_super) {
  72498. __extends(HingeJoint, _super);
  72499. function HingeJoint(jointData) {
  72500. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  72501. }
  72502. /**
  72503. * Set the motor values.
  72504. * Attention, this function is plugin specific. Engines won't react 100% the same.
  72505. * @param {number} force the force to apply
  72506. * @param {number} maxForce max force for this motor.
  72507. */
  72508. HingeJoint.prototype.setMotor = function (force, maxForce) {
  72509. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  72510. };
  72511. /**
  72512. * Set the motor's limits.
  72513. * Attention, this function is plugin specific. Engines won't react 100% the same.
  72514. */
  72515. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  72516. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  72517. };
  72518. return HingeJoint;
  72519. }(MotorEnabledJoint));
  72520. BABYLON.HingeJoint = HingeJoint;
  72521. /**
  72522. * This class represents a dual hinge physics joint (same as wheel joint)
  72523. */
  72524. var Hinge2Joint = /** @class */ (function (_super) {
  72525. __extends(Hinge2Joint, _super);
  72526. function Hinge2Joint(jointData) {
  72527. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  72528. }
  72529. /**
  72530. * Set the motor values.
  72531. * Attention, this function is plugin specific. Engines won't react 100% the same.
  72532. * @param {number} force the force to apply
  72533. * @param {number} maxForce max force for this motor.
  72534. * @param {motorIndex} the motor's index, 0 or 1.
  72535. */
  72536. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  72537. if (motorIndex === void 0) { motorIndex = 0; }
  72538. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  72539. };
  72540. /**
  72541. * Set the motor limits.
  72542. * Attention, this function is plugin specific. Engines won't react 100% the same.
  72543. * @param {number} upperLimit the upper limit
  72544. * @param {number} lowerLimit lower limit
  72545. * @param {motorIndex} the motor's index, 0 or 1.
  72546. */
  72547. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  72548. if (motorIndex === void 0) { motorIndex = 0; }
  72549. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  72550. };
  72551. return Hinge2Joint;
  72552. }(MotorEnabledJoint));
  72553. BABYLON.Hinge2Joint = Hinge2Joint;
  72554. })(BABYLON || (BABYLON = {}));
  72555. //# sourceMappingURL=babylon.physicsJoint.js.map
  72556. var BABYLON;
  72557. (function (BABYLON) {
  72558. var PhysicsImpostor = /** @class */ (function () {
  72559. function PhysicsImpostor(object, type, _options, _scene) {
  72560. if (_options === void 0) { _options = { mass: 0 }; }
  72561. var _this = this;
  72562. this.object = object;
  72563. this.type = type;
  72564. this._options = _options;
  72565. this._scene = _scene;
  72566. this._bodyUpdateRequired = false;
  72567. this._onBeforePhysicsStepCallbacks = new Array();
  72568. this._onAfterPhysicsStepCallbacks = new Array();
  72569. this._onPhysicsCollideCallbacks = [];
  72570. this._deltaPosition = BABYLON.Vector3.Zero();
  72571. this._isDisposed = false;
  72572. //temp variables for parent rotation calculations
  72573. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  72574. this._tmpQuat = new BABYLON.Quaternion();
  72575. this._tmpQuat2 = new BABYLON.Quaternion();
  72576. /**
  72577. * this function is executed by the physics engine.
  72578. */
  72579. this.beforeStep = function () {
  72580. if (!_this._physicsEngine) {
  72581. return;
  72582. }
  72583. _this.object.translate(_this._deltaPosition, -1);
  72584. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  72585. _this.object.computeWorldMatrix(false);
  72586. if (_this.object.parent && _this.object.rotationQuaternion) {
  72587. _this.getParentsRotation();
  72588. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  72589. }
  72590. else {
  72591. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  72592. }
  72593. if (!_this._options.disableBidirectionalTransformation) {
  72594. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  72595. }
  72596. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  72597. func(_this);
  72598. });
  72599. };
  72600. /**
  72601. * this function is executed by the physics engine.
  72602. */
  72603. this.afterStep = function () {
  72604. if (!_this._physicsEngine) {
  72605. return;
  72606. }
  72607. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  72608. func(_this);
  72609. });
  72610. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  72611. // object has now its world rotation. needs to be converted to local.
  72612. if (_this.object.parent && _this.object.rotationQuaternion) {
  72613. _this.getParentsRotation();
  72614. _this._tmpQuat.conjugateInPlace();
  72615. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  72616. }
  72617. // take the position set and make it the absolute position of this object.
  72618. _this.object.setAbsolutePosition(_this.object.position);
  72619. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  72620. _this.object.translate(_this._deltaPosition, 1);
  72621. };
  72622. /**
  72623. * Legacy collision detection event support
  72624. */
  72625. this.onCollideEvent = null;
  72626. //event and body object due to cannon's event-based architecture.
  72627. this.onCollide = function (e) {
  72628. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  72629. return;
  72630. }
  72631. if (!_this._physicsEngine) {
  72632. return;
  72633. }
  72634. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  72635. if (otherImpostor) {
  72636. // Legacy collision detection event support
  72637. if (_this.onCollideEvent) {
  72638. _this.onCollideEvent(_this, otherImpostor);
  72639. }
  72640. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  72641. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  72642. }).forEach(function (obj) {
  72643. obj.callback(_this, otherImpostor);
  72644. });
  72645. }
  72646. };
  72647. //sanity check!
  72648. if (!this.object) {
  72649. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  72650. return;
  72651. }
  72652. //legacy support for old syntax.
  72653. if (!this._scene && object.getScene) {
  72654. this._scene = object.getScene();
  72655. }
  72656. if (!this._scene) {
  72657. return;
  72658. }
  72659. this._physicsEngine = this._scene.getPhysicsEngine();
  72660. if (!this._physicsEngine) {
  72661. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  72662. }
  72663. else {
  72664. //set the object's quaternion, if not set
  72665. if (!this.object.rotationQuaternion) {
  72666. if (this.object.rotation) {
  72667. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  72668. }
  72669. else {
  72670. this.object.rotationQuaternion = new BABYLON.Quaternion();
  72671. }
  72672. }
  72673. //default options params
  72674. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  72675. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  72676. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  72677. this._joints = [];
  72678. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  72679. if (!this.object.parent || this._options.ignoreParent) {
  72680. this._init();
  72681. }
  72682. else if (this.object.parent.physicsImpostor) {
  72683. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  72684. }
  72685. }
  72686. }
  72687. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  72688. get: function () {
  72689. return this._isDisposed;
  72690. },
  72691. enumerable: true,
  72692. configurable: true
  72693. });
  72694. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  72695. get: function () {
  72696. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  72697. },
  72698. set: function (value) {
  72699. this.setMass(value);
  72700. },
  72701. enumerable: true,
  72702. configurable: true
  72703. });
  72704. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  72705. get: function () {
  72706. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  72707. },
  72708. set: function (value) {
  72709. if (!this._physicsEngine) {
  72710. return;
  72711. }
  72712. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  72713. },
  72714. enumerable: true,
  72715. configurable: true
  72716. });
  72717. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  72718. get: function () {
  72719. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  72720. },
  72721. set: function (value) {
  72722. if (!this._physicsEngine) {
  72723. return;
  72724. }
  72725. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  72726. },
  72727. enumerable: true,
  72728. configurable: true
  72729. });
  72730. /**
  72731. * This function will completly initialize this impostor.
  72732. * It will create a new body - but only if this mesh has no parent.
  72733. * If it has, this impostor will not be used other than to define the impostor
  72734. * of the child mesh.
  72735. */
  72736. PhysicsImpostor.prototype._init = function () {
  72737. if (!this._physicsEngine) {
  72738. return;
  72739. }
  72740. this._physicsEngine.removeImpostor(this);
  72741. this.physicsBody = null;
  72742. this._parent = this._parent || this._getPhysicsParent();
  72743. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  72744. this._physicsEngine.addImpostor(this);
  72745. }
  72746. };
  72747. PhysicsImpostor.prototype._getPhysicsParent = function () {
  72748. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  72749. var parentMesh = this.object.parent;
  72750. return parentMesh.physicsImpostor;
  72751. }
  72752. return null;
  72753. };
  72754. /**
  72755. * Should a new body be generated.
  72756. */
  72757. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  72758. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  72759. };
  72760. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  72761. this.forceUpdate();
  72762. };
  72763. /**
  72764. * Force a regeneration of this or the parent's impostor's body.
  72765. * Use under cautious - This will remove all joints already implemented.
  72766. */
  72767. PhysicsImpostor.prototype.forceUpdate = function () {
  72768. this._init();
  72769. if (this.parent && !this._options.ignoreParent) {
  72770. this.parent.forceUpdate();
  72771. }
  72772. };
  72773. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  72774. /*public get mesh(): AbstractMesh {
  72775. return this._mesh;
  72776. }*/
  72777. /**
  72778. * Gets the body that holds this impostor. Either its own, or its parent.
  72779. */
  72780. get: function () {
  72781. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  72782. },
  72783. /**
  72784. * Set the physics body. Used mainly by the physics engine/plugin
  72785. */
  72786. set: function (physicsBody) {
  72787. if (this._physicsBody && this._physicsEngine) {
  72788. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  72789. }
  72790. this._physicsBody = physicsBody;
  72791. this.resetUpdateFlags();
  72792. },
  72793. enumerable: true,
  72794. configurable: true
  72795. });
  72796. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  72797. get: function () {
  72798. return !this._options.ignoreParent && this._parent ? this._parent : null;
  72799. },
  72800. set: function (value) {
  72801. this._parent = value;
  72802. },
  72803. enumerable: true,
  72804. configurable: true
  72805. });
  72806. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  72807. this._bodyUpdateRequired = false;
  72808. };
  72809. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  72810. if (this.object.getBoundingInfo) {
  72811. var q = this.object.rotationQuaternion;
  72812. //reset rotation
  72813. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  72814. //calculate the world matrix with no rotation
  72815. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  72816. var boundingInfo = this.object.getBoundingInfo();
  72817. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  72818. //bring back the rotation
  72819. this.object.rotationQuaternion = q;
  72820. //calculate the world matrix with the new rotation
  72821. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  72822. return size;
  72823. }
  72824. else {
  72825. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  72826. }
  72827. };
  72828. PhysicsImpostor.prototype.getObjectCenter = function () {
  72829. if (this.object.getBoundingInfo) {
  72830. var boundingInfo = this.object.getBoundingInfo();
  72831. return boundingInfo.boundingBox.centerWorld;
  72832. }
  72833. else {
  72834. return this.object.position;
  72835. }
  72836. };
  72837. /**
  72838. * Get a specific parametes from the options parameter.
  72839. */
  72840. PhysicsImpostor.prototype.getParam = function (paramName) {
  72841. return this._options[paramName];
  72842. };
  72843. /**
  72844. * Sets a specific parameter in the options given to the physics plugin
  72845. */
  72846. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  72847. this._options[paramName] = value;
  72848. this._bodyUpdateRequired = true;
  72849. };
  72850. /**
  72851. * Specifically change the body's mass option. Won't recreate the physics body object
  72852. */
  72853. PhysicsImpostor.prototype.setMass = function (mass) {
  72854. if (this.getParam("mass") !== mass) {
  72855. this.setParam("mass", mass);
  72856. }
  72857. if (this._physicsEngine) {
  72858. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  72859. }
  72860. };
  72861. PhysicsImpostor.prototype.getLinearVelocity = function () {
  72862. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  72863. };
  72864. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  72865. if (this._physicsEngine) {
  72866. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  72867. }
  72868. };
  72869. PhysicsImpostor.prototype.getAngularVelocity = function () {
  72870. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  72871. };
  72872. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  72873. if (this._physicsEngine) {
  72874. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  72875. }
  72876. };
  72877. /**
  72878. * Execute a function with the physics plugin native code.
  72879. * Provide a function the will have two variables - the world object and the physics body object.
  72880. */
  72881. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  72882. if (this._physicsEngine) {
  72883. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  72884. }
  72885. };
  72886. /**
  72887. * Register a function that will be executed before the physics world is stepping forward.
  72888. */
  72889. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  72890. this._onBeforePhysicsStepCallbacks.push(func);
  72891. };
  72892. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  72893. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  72894. if (index > -1) {
  72895. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  72896. }
  72897. else {
  72898. BABYLON.Tools.Warn("Function to remove was not found");
  72899. }
  72900. };
  72901. /**
  72902. * Register a function that will be executed after the physics step
  72903. */
  72904. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  72905. this._onAfterPhysicsStepCallbacks.push(func);
  72906. };
  72907. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  72908. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  72909. if (index > -1) {
  72910. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  72911. }
  72912. else {
  72913. BABYLON.Tools.Warn("Function to remove was not found");
  72914. }
  72915. };
  72916. /**
  72917. * register a function that will be executed when this impostor collides against a different body.
  72918. */
  72919. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  72920. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  72921. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  72922. };
  72923. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  72924. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  72925. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  72926. if (index > -1) {
  72927. this._onPhysicsCollideCallbacks.splice(index, 1);
  72928. }
  72929. else {
  72930. BABYLON.Tools.Warn("Function to remove was not found");
  72931. }
  72932. };
  72933. PhysicsImpostor.prototype.getParentsRotation = function () {
  72934. var parent = this.object.parent;
  72935. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  72936. while (parent) {
  72937. if (parent.rotationQuaternion) {
  72938. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  72939. }
  72940. else {
  72941. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  72942. }
  72943. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  72944. parent = parent.parent;
  72945. }
  72946. return this._tmpQuat;
  72947. };
  72948. /**
  72949. * Apply a force
  72950. */
  72951. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  72952. if (this._physicsEngine) {
  72953. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  72954. }
  72955. return this;
  72956. };
  72957. /**
  72958. * Apply an impulse
  72959. */
  72960. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  72961. if (this._physicsEngine) {
  72962. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  72963. }
  72964. return this;
  72965. };
  72966. /**
  72967. * A help function to create a joint.
  72968. */
  72969. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  72970. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  72971. this.addJoint(otherImpostor, joint);
  72972. return this;
  72973. };
  72974. /**
  72975. * Add a joint to this impostor with a different impostor.
  72976. */
  72977. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  72978. this._joints.push({
  72979. otherImpostor: otherImpostor,
  72980. joint: joint
  72981. });
  72982. if (this._physicsEngine) {
  72983. this._physicsEngine.addJoint(this, otherImpostor, joint);
  72984. }
  72985. return this;
  72986. };
  72987. /**
  72988. * Will keep this body still, in a sleep mode.
  72989. */
  72990. PhysicsImpostor.prototype.sleep = function () {
  72991. if (this._physicsEngine) {
  72992. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  72993. }
  72994. return this;
  72995. };
  72996. /**
  72997. * Wake the body up.
  72998. */
  72999. PhysicsImpostor.prototype.wakeUp = function () {
  73000. if (this._physicsEngine) {
  73001. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  73002. }
  73003. return this;
  73004. };
  73005. PhysicsImpostor.prototype.clone = function (newObject) {
  73006. if (!newObject)
  73007. return null;
  73008. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  73009. };
  73010. PhysicsImpostor.prototype.dispose = function () {
  73011. var _this = this;
  73012. //no dispose if no physics engine is available.
  73013. if (!this._physicsEngine) {
  73014. return;
  73015. }
  73016. this._joints.forEach(function (j) {
  73017. if (_this._physicsEngine) {
  73018. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  73019. }
  73020. });
  73021. //dispose the physics body
  73022. this._physicsEngine.removeImpostor(this);
  73023. if (this.parent) {
  73024. this.parent.forceUpdate();
  73025. }
  73026. else {
  73027. /*this._object.getChildMeshes().forEach(function(mesh) {
  73028. if (mesh.physicsImpostor) {
  73029. if (disposeChildren) {
  73030. mesh.physicsImpostor.dispose();
  73031. mesh.physicsImpostor = null;
  73032. }
  73033. }
  73034. })*/
  73035. }
  73036. this._isDisposed = true;
  73037. };
  73038. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  73039. this._deltaPosition.copyFrom(position);
  73040. };
  73041. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  73042. if (!this._deltaRotation) {
  73043. this._deltaRotation = new BABYLON.Quaternion();
  73044. }
  73045. this._deltaRotation.copyFrom(rotation);
  73046. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  73047. };
  73048. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  73049. if (this._physicsEngine) {
  73050. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  73051. }
  73052. return this;
  73053. };
  73054. PhysicsImpostor.prototype.getRadius = function () {
  73055. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  73056. };
  73057. /**
  73058. * Sync a bone with this impostor
  73059. * @param bone The bone to sync to the impostor.
  73060. * @param boneMesh The mesh that the bone is influencing.
  73061. * @param jointPivot The pivot of the joint / bone in local space.
  73062. * @param distToJoint Optional distance from the impostor to the joint.
  73063. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  73064. */
  73065. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  73066. var tempVec = PhysicsImpostor._tmpVecs[0];
  73067. var mesh = this.object;
  73068. if (mesh.rotationQuaternion) {
  73069. if (adjustRotation) {
  73070. var tempQuat = PhysicsImpostor._tmpQuat;
  73071. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  73072. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  73073. }
  73074. else {
  73075. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  73076. }
  73077. }
  73078. tempVec.x = 0;
  73079. tempVec.y = 0;
  73080. tempVec.z = 0;
  73081. if (jointPivot) {
  73082. tempVec.x = jointPivot.x;
  73083. tempVec.y = jointPivot.y;
  73084. tempVec.z = jointPivot.z;
  73085. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  73086. if (distToJoint === undefined || distToJoint === null) {
  73087. distToJoint = jointPivot.length();
  73088. }
  73089. tempVec.x *= distToJoint;
  73090. tempVec.y *= distToJoint;
  73091. tempVec.z *= distToJoint;
  73092. }
  73093. if (bone.getParent()) {
  73094. tempVec.addInPlace(mesh.getAbsolutePosition());
  73095. bone.setAbsolutePosition(tempVec, boneMesh);
  73096. }
  73097. else {
  73098. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  73099. boneMesh.position.x -= tempVec.x;
  73100. boneMesh.position.y -= tempVec.y;
  73101. boneMesh.position.z -= tempVec.z;
  73102. }
  73103. };
  73104. /**
  73105. * Sync impostor to a bone
  73106. * @param bone The bone that the impostor will be synced to.
  73107. * @param boneMesh The mesh that the bone is influencing.
  73108. * @param jointPivot The pivot of the joint / bone in local space.
  73109. * @param distToJoint Optional distance from the impostor to the joint.
  73110. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  73111. * @param boneAxis Optional vector3 axis the bone is aligned with
  73112. */
  73113. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  73114. var mesh = this.object;
  73115. if (mesh.rotationQuaternion) {
  73116. if (adjustRotation) {
  73117. var tempQuat = PhysicsImpostor._tmpQuat;
  73118. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  73119. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  73120. }
  73121. else {
  73122. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  73123. }
  73124. }
  73125. var pos = PhysicsImpostor._tmpVecs[0];
  73126. var boneDir = PhysicsImpostor._tmpVecs[1];
  73127. if (!boneAxis) {
  73128. boneAxis = PhysicsImpostor._tmpVecs[2];
  73129. boneAxis.x = 0;
  73130. boneAxis.y = 1;
  73131. boneAxis.z = 0;
  73132. }
  73133. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  73134. bone.getAbsolutePositionToRef(boneMesh, pos);
  73135. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  73136. distToJoint = jointPivot.length();
  73137. }
  73138. if (distToJoint !== undefined && distToJoint !== null) {
  73139. pos.x += boneDir.x * distToJoint;
  73140. pos.y += boneDir.y * distToJoint;
  73141. pos.z += boneDir.z * distToJoint;
  73142. }
  73143. mesh.setAbsolutePosition(pos);
  73144. };
  73145. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  73146. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  73147. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73148. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  73149. //Impostor types
  73150. PhysicsImpostor.NoImpostor = 0;
  73151. PhysicsImpostor.SphereImpostor = 1;
  73152. PhysicsImpostor.BoxImpostor = 2;
  73153. PhysicsImpostor.PlaneImpostor = 3;
  73154. PhysicsImpostor.MeshImpostor = 4;
  73155. PhysicsImpostor.CylinderImpostor = 7;
  73156. PhysicsImpostor.ParticleImpostor = 8;
  73157. PhysicsImpostor.HeightmapImpostor = 9;
  73158. return PhysicsImpostor;
  73159. }());
  73160. BABYLON.PhysicsImpostor = PhysicsImpostor;
  73161. })(BABYLON || (BABYLON = {}));
  73162. //# sourceMappingURL=babylon.physicsImpostor.js.map
  73163. var BABYLON;
  73164. (function (BABYLON) {
  73165. var PhysicsEngine = /** @class */ (function () {
  73166. function PhysicsEngine(gravity, _physicsPlugin) {
  73167. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  73168. this._physicsPlugin = _physicsPlugin;
  73169. //new methods and parameters
  73170. this._impostors = [];
  73171. this._joints = [];
  73172. if (!this._physicsPlugin.isSupported()) {
  73173. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  73174. + "Please make sure it is included.");
  73175. }
  73176. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  73177. this.setGravity(gravity);
  73178. this.setTimeStep();
  73179. }
  73180. PhysicsEngine.prototype.setGravity = function (gravity) {
  73181. this.gravity = gravity;
  73182. this._physicsPlugin.setGravity(this.gravity);
  73183. };
  73184. /**
  73185. * Set the time step of the physics engine.
  73186. * default is 1/60.
  73187. * To slow it down, enter 1/600 for example.
  73188. * To speed it up, 1/30
  73189. * @param {number} newTimeStep the new timestep to apply to this world.
  73190. */
  73191. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  73192. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  73193. this._physicsPlugin.setTimeStep(newTimeStep);
  73194. };
  73195. /**
  73196. * Get the time step of the physics engine.
  73197. */
  73198. PhysicsEngine.prototype.getTimeStep = function () {
  73199. return this._physicsPlugin.getTimeStep();
  73200. };
  73201. PhysicsEngine.prototype.dispose = function () {
  73202. this._impostors.forEach(function (impostor) {
  73203. impostor.dispose();
  73204. });
  73205. this._physicsPlugin.dispose();
  73206. };
  73207. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  73208. return this._physicsPlugin.name;
  73209. };
  73210. /**
  73211. * Adding a new impostor for the impostor tracking.
  73212. * This will be done by the impostor itself.
  73213. * @param {PhysicsImpostor} impostor the impostor to add
  73214. */
  73215. PhysicsEngine.prototype.addImpostor = function (impostor) {
  73216. impostor.uniqueId = this._impostors.push(impostor);
  73217. //if no parent, generate the body
  73218. if (!impostor.parent) {
  73219. this._physicsPlugin.generatePhysicsBody(impostor);
  73220. }
  73221. };
  73222. /**
  73223. * Remove an impostor from the engine.
  73224. * This impostor and its mesh will not longer be updated by the physics engine.
  73225. * @param {PhysicsImpostor} impostor the impostor to remove
  73226. */
  73227. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  73228. var index = this._impostors.indexOf(impostor);
  73229. if (index > -1) {
  73230. var removed = this._impostors.splice(index, 1);
  73231. //Is it needed?
  73232. if (removed.length) {
  73233. //this will also remove it from the world.
  73234. removed[0].physicsBody = null;
  73235. }
  73236. }
  73237. };
  73238. /**
  73239. * Add a joint to the physics engine
  73240. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  73241. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  73242. * @param {PhysicsJoint} the joint that will connect both impostors.
  73243. */
  73244. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  73245. var impostorJoint = {
  73246. mainImpostor: mainImpostor,
  73247. connectedImpostor: connectedImpostor,
  73248. joint: joint
  73249. };
  73250. joint.physicsPlugin = this._physicsPlugin;
  73251. this._joints.push(impostorJoint);
  73252. this._physicsPlugin.generateJoint(impostorJoint);
  73253. };
  73254. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  73255. var matchingJoints = this._joints.filter(function (impostorJoint) {
  73256. return (impostorJoint.connectedImpostor === connectedImpostor
  73257. && impostorJoint.joint === joint
  73258. && impostorJoint.mainImpostor === mainImpostor);
  73259. });
  73260. if (matchingJoints.length) {
  73261. this._physicsPlugin.removeJoint(matchingJoints[0]);
  73262. //TODO remove it from the list as well
  73263. }
  73264. };
  73265. /**
  73266. * Called by the scene. no need to call it.
  73267. */
  73268. PhysicsEngine.prototype._step = function (delta) {
  73269. var _this = this;
  73270. //check if any mesh has no body / requires an update
  73271. this._impostors.forEach(function (impostor) {
  73272. if (impostor.isBodyInitRequired()) {
  73273. _this._physicsPlugin.generatePhysicsBody(impostor);
  73274. }
  73275. });
  73276. if (delta > 0.1) {
  73277. delta = 0.1;
  73278. }
  73279. else if (delta <= 0) {
  73280. delta = 1.0 / 60.0;
  73281. }
  73282. this._physicsPlugin.executeStep(delta, this._impostors);
  73283. };
  73284. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  73285. return this._physicsPlugin;
  73286. };
  73287. PhysicsEngine.prototype.getImpostors = function () {
  73288. return this._impostors;
  73289. };
  73290. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  73291. for (var i = 0; i < this._impostors.length; ++i) {
  73292. if (this._impostors[i].object === object) {
  73293. return this._impostors[i];
  73294. }
  73295. }
  73296. return null;
  73297. };
  73298. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  73299. for (var i = 0; i < this._impostors.length; ++i) {
  73300. if (this._impostors[i].physicsBody === body) {
  73301. return this._impostors[i];
  73302. }
  73303. }
  73304. return null;
  73305. };
  73306. // Statics
  73307. PhysicsEngine.Epsilon = 0.001;
  73308. return PhysicsEngine;
  73309. }());
  73310. BABYLON.PhysicsEngine = PhysicsEngine;
  73311. })(BABYLON || (BABYLON = {}));
  73312. //# sourceMappingURL=babylon.physicsEngine.js.map
  73313. var BABYLON;
  73314. (function (BABYLON) {
  73315. var PhysicsHelper = /** @class */ (function () {
  73316. function PhysicsHelper(scene) {
  73317. this._scene = scene;
  73318. this._physicsEngine = this._scene.getPhysicsEngine();
  73319. if (!this._physicsEngine) {
  73320. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  73321. }
  73322. }
  73323. /**
  73324. * @param {Vector3} origin the origin of the explosion
  73325. * @param {number} radius the explosion radius
  73326. * @param {number} strength the explosion strength
  73327. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  73328. */
  73329. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  73330. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  73331. if (!this._physicsEngine) {
  73332. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  73333. return null;
  73334. }
  73335. var impostors = this._physicsEngine.getImpostors();
  73336. if (impostors.length === 0) {
  73337. return null;
  73338. }
  73339. var event = new PhysicsRadialExplosionEvent(this._scene);
  73340. impostors.forEach(function (impostor) {
  73341. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  73342. if (!impostorForceAndContactPoint) {
  73343. return;
  73344. }
  73345. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  73346. });
  73347. event.dispose(false);
  73348. return event;
  73349. };
  73350. /**
  73351. * @param {Vector3} origin the origin of the explosion
  73352. * @param {number} radius the explosion radius
  73353. * @param {number} strength the explosion strength
  73354. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  73355. */
  73356. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  73357. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  73358. if (!this._physicsEngine) {
  73359. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  73360. return null;
  73361. }
  73362. var impostors = this._physicsEngine.getImpostors();
  73363. if (impostors.length === 0) {
  73364. return null;
  73365. }
  73366. var event = new PhysicsRadialExplosionEvent(this._scene);
  73367. impostors.forEach(function (impostor) {
  73368. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  73369. if (!impostorForceAndContactPoint) {
  73370. return;
  73371. }
  73372. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  73373. });
  73374. event.dispose(false);
  73375. return event;
  73376. };
  73377. /**
  73378. * @param {Vector3} origin the origin of the explosion
  73379. * @param {number} radius the explosion radius
  73380. * @param {number} strength the explosion strength
  73381. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  73382. */
  73383. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  73384. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  73385. if (!this._physicsEngine) {
  73386. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  73387. return null;
  73388. }
  73389. var impostors = this._physicsEngine.getImpostors();
  73390. if (impostors.length === 0) {
  73391. return null;
  73392. }
  73393. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  73394. event.dispose(false);
  73395. return event;
  73396. };
  73397. /**
  73398. * @param {Vector3} origin the origin of the updraft
  73399. * @param {number} radius the radius of the updraft
  73400. * @param {number} strength the strength of the updraft
  73401. * @param {number} height the height of the updraft
  73402. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  73403. */
  73404. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  73405. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  73406. if (!this._physicsEngine) {
  73407. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  73408. return null;
  73409. }
  73410. if (this._physicsEngine.getImpostors().length === 0) {
  73411. return null;
  73412. }
  73413. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  73414. event.dispose(false);
  73415. return event;
  73416. };
  73417. /**
  73418. * @param {Vector3} origin the of the vortex
  73419. * @param {number} radius the radius of the vortex
  73420. * @param {number} strength the strength of the vortex
  73421. * @param {number} height the height of the vortex
  73422. */
  73423. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  73424. if (!this._physicsEngine) {
  73425. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  73426. return null;
  73427. }
  73428. if (this._physicsEngine.getImpostors().length === 0) {
  73429. return null;
  73430. }
  73431. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  73432. event.dispose(false);
  73433. return event;
  73434. };
  73435. return PhysicsHelper;
  73436. }());
  73437. BABYLON.PhysicsHelper = PhysicsHelper;
  73438. /***** Radial explosion *****/
  73439. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  73440. function PhysicsRadialExplosionEvent(scene) {
  73441. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  73442. this._rays = [];
  73443. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  73444. this._scene = scene;
  73445. }
  73446. /**
  73447. * Returns the data related to the radial explosion event (sphere & rays).
  73448. * @returns {PhysicsRadialExplosionEventData}
  73449. */
  73450. PhysicsRadialExplosionEvent.prototype.getData = function () {
  73451. this._dataFetched = true;
  73452. return {
  73453. sphere: this._sphere,
  73454. rays: this._rays,
  73455. };
  73456. };
  73457. /**
  73458. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  73459. * @param impostor
  73460. * @param {Vector3} origin the origin of the explosion
  73461. * @param {number} radius the explosion radius
  73462. * @param {number} strength the explosion strength
  73463. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  73464. * @returns {Nullable<PhysicsForceAndContactPoint>}
  73465. */
  73466. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  73467. if (impostor.mass === 0) {
  73468. return null;
  73469. }
  73470. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  73471. return null;
  73472. }
  73473. if (impostor.object.getClassName() !== 'Mesh') {
  73474. return null;
  73475. }
  73476. var impostorObject = impostor.object;
  73477. var impostorObjectCenter = impostor.getObjectCenter();
  73478. var direction = impostorObjectCenter.subtract(origin);
  73479. var ray = new BABYLON.Ray(origin, direction, radius);
  73480. this._rays.push(ray);
  73481. var hit = ray.intersectsMesh(impostorObject);
  73482. var contactPoint = hit.pickedPoint;
  73483. if (!contactPoint) {
  73484. return null;
  73485. }
  73486. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  73487. if (distanceFromOrigin > radius) {
  73488. return null;
  73489. }
  73490. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  73491. ? strength
  73492. : strength * (1 - (distanceFromOrigin / radius));
  73493. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  73494. return { force: force, contactPoint: contactPoint };
  73495. };
  73496. /**
  73497. * Disposes the sphere.
  73498. * @param {bolean} force
  73499. */
  73500. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  73501. var _this = this;
  73502. if (force === void 0) { force = true; }
  73503. if (force) {
  73504. this._sphere.dispose();
  73505. }
  73506. else {
  73507. setTimeout(function () {
  73508. if (!_this._dataFetched) {
  73509. _this._sphere.dispose();
  73510. }
  73511. }, 0);
  73512. }
  73513. };
  73514. /*** Helpers ***/
  73515. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  73516. if (!this._sphere) {
  73517. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  73518. this._sphere.isVisible = false;
  73519. }
  73520. };
  73521. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  73522. var impostorObject = impostor.object;
  73523. this._prepareSphere();
  73524. this._sphere.position = origin;
  73525. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  73526. this._sphere._updateBoundingInfo();
  73527. this._sphere.computeWorldMatrix(true);
  73528. return this._sphere.intersectsMesh(impostorObject, true);
  73529. };
  73530. return PhysicsRadialExplosionEvent;
  73531. }());
  73532. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  73533. /***** Gravitational Field *****/
  73534. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  73535. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  73536. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  73537. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  73538. this._physicsHelper = physicsHelper;
  73539. this._scene = scene;
  73540. this._origin = origin;
  73541. this._radius = radius;
  73542. this._strength = strength;
  73543. this._falloff = falloff;
  73544. this._tickCallback = this._tick.bind(this);
  73545. }
  73546. /**
  73547. * Returns the data related to the gravitational field event (sphere).
  73548. * @returns {PhysicsGravitationalFieldEventData}
  73549. */
  73550. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  73551. this._dataFetched = true;
  73552. return {
  73553. sphere: this._sphere,
  73554. };
  73555. };
  73556. /**
  73557. * Enables the gravitational field.
  73558. */
  73559. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  73560. this._tickCallback.call(this);
  73561. this._scene.registerBeforeRender(this._tickCallback);
  73562. };
  73563. /**
  73564. * Disables the gravitational field.
  73565. */
  73566. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  73567. this._scene.unregisterBeforeRender(this._tickCallback);
  73568. };
  73569. /**
  73570. * Disposes the sphere.
  73571. * @param {bolean} force
  73572. */
  73573. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  73574. var _this = this;
  73575. if (force === void 0) { force = true; }
  73576. if (force) {
  73577. this._sphere.dispose();
  73578. }
  73579. else {
  73580. setTimeout(function () {
  73581. if (!_this._dataFetched) {
  73582. _this._sphere.dispose();
  73583. }
  73584. }, 0);
  73585. }
  73586. };
  73587. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  73588. // Since the params won't change, we fetch the event only once
  73589. if (this._sphere) {
  73590. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  73591. }
  73592. else {
  73593. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  73594. if (radialExplosionEvent) {
  73595. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  73596. }
  73597. }
  73598. };
  73599. return PhysicsGravitationalFieldEvent;
  73600. }());
  73601. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  73602. /***** Updraft *****/
  73603. var PhysicsUpdraftEvent = /** @class */ (function () {
  73604. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  73605. this._scene = _scene;
  73606. this._origin = _origin;
  73607. this._radius = _radius;
  73608. this._strength = _strength;
  73609. this._height = _height;
  73610. this._updraftMode = _updraftMode;
  73611. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  73612. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  73613. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  73614. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  73615. this._physicsEngine = this._scene.getPhysicsEngine();
  73616. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  73617. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  73618. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  73619. this._originDirection = this._origin.subtract(this._originTop).normalize();
  73620. }
  73621. this._tickCallback = this._tick.bind(this);
  73622. }
  73623. /**
  73624. * Returns the data related to the updraft event (cylinder).
  73625. * @returns {PhysicsUpdraftEventData}
  73626. */
  73627. PhysicsUpdraftEvent.prototype.getData = function () {
  73628. this._dataFetched = true;
  73629. return {
  73630. cylinder: this._cylinder,
  73631. };
  73632. };
  73633. /**
  73634. * Enables the updraft.
  73635. */
  73636. PhysicsUpdraftEvent.prototype.enable = function () {
  73637. this._tickCallback.call(this);
  73638. this._scene.registerBeforeRender(this._tickCallback);
  73639. };
  73640. /**
  73641. * Disables the cortex.
  73642. */
  73643. PhysicsUpdraftEvent.prototype.disable = function () {
  73644. this._scene.unregisterBeforeRender(this._tickCallback);
  73645. };
  73646. /**
  73647. * Disposes the sphere.
  73648. * @param {bolean} force
  73649. */
  73650. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  73651. var _this = this;
  73652. if (force === void 0) { force = true; }
  73653. if (force) {
  73654. this._cylinder.dispose();
  73655. }
  73656. else {
  73657. setTimeout(function () {
  73658. if (!_this._dataFetched) {
  73659. _this._cylinder.dispose();
  73660. }
  73661. }, 0);
  73662. }
  73663. };
  73664. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  73665. if (impostor.mass === 0) {
  73666. return null;
  73667. }
  73668. if (!this._intersectsWithCylinder(impostor)) {
  73669. return null;
  73670. }
  73671. var impostorObjectCenter = impostor.getObjectCenter();
  73672. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  73673. var direction = this._originDirection;
  73674. }
  73675. else {
  73676. var direction = impostorObjectCenter.subtract(this._originTop);
  73677. }
  73678. var multiplier = this._strength * -1;
  73679. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  73680. return { force: force, contactPoint: impostorObjectCenter };
  73681. };
  73682. PhysicsUpdraftEvent.prototype._tick = function () {
  73683. var _this = this;
  73684. this._physicsEngine.getImpostors().forEach(function (impostor) {
  73685. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  73686. if (!impostorForceAndContactPoint) {
  73687. return;
  73688. }
  73689. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  73690. });
  73691. };
  73692. /*** Helpers ***/
  73693. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  73694. if (!this._cylinder) {
  73695. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  73696. height: this._height,
  73697. diameter: this._radius * 2,
  73698. }, this._scene);
  73699. this._cylinder.isVisible = false;
  73700. }
  73701. };
  73702. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  73703. var impostorObject = impostor.object;
  73704. this._prepareCylinder();
  73705. this._cylinder.position = this._cylinderPosition;
  73706. return this._cylinder.intersectsMesh(impostorObject, true);
  73707. };
  73708. return PhysicsUpdraftEvent;
  73709. }());
  73710. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  73711. /***** Vortex *****/
  73712. var PhysicsVortexEvent = /** @class */ (function () {
  73713. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  73714. this._scene = _scene;
  73715. this._origin = _origin;
  73716. this._radius = _radius;
  73717. this._strength = _strength;
  73718. this._height = _height;
  73719. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  73720. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  73721. this._updraftMultiplier = 0.02;
  73722. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  73723. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  73724. this._physicsEngine = this._scene.getPhysicsEngine();
  73725. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  73726. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  73727. this._tickCallback = this._tick.bind(this);
  73728. }
  73729. /**
  73730. * Returns the data related to the vortex event (cylinder).
  73731. * @returns {PhysicsVortexEventData}
  73732. */
  73733. PhysicsVortexEvent.prototype.getData = function () {
  73734. this._dataFetched = true;
  73735. return {
  73736. cylinder: this._cylinder,
  73737. };
  73738. };
  73739. /**
  73740. * Enables the vortex.
  73741. */
  73742. PhysicsVortexEvent.prototype.enable = function () {
  73743. this._tickCallback.call(this);
  73744. this._scene.registerBeforeRender(this._tickCallback);
  73745. };
  73746. /**
  73747. * Disables the cortex.
  73748. */
  73749. PhysicsVortexEvent.prototype.disable = function () {
  73750. this._scene.unregisterBeforeRender(this._tickCallback);
  73751. };
  73752. /**
  73753. * Disposes the sphere.
  73754. * @param {bolean} force
  73755. */
  73756. PhysicsVortexEvent.prototype.dispose = function (force) {
  73757. var _this = this;
  73758. if (force === void 0) { force = true; }
  73759. if (force) {
  73760. this._cylinder.dispose();
  73761. }
  73762. else {
  73763. setTimeout(function () {
  73764. if (!_this._dataFetched) {
  73765. _this._cylinder.dispose();
  73766. }
  73767. }, 0);
  73768. }
  73769. };
  73770. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  73771. if (impostor.mass === 0) {
  73772. return null;
  73773. }
  73774. if (!this._intersectsWithCylinder(impostor)) {
  73775. return null;
  73776. }
  73777. if (impostor.object.getClassName() !== 'Mesh') {
  73778. return null;
  73779. }
  73780. var impostorObject = impostor.object;
  73781. var impostorObjectCenter = impostor.getObjectCenter();
  73782. 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)
  73783. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  73784. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  73785. var hit = ray.intersectsMesh(impostorObject);
  73786. var contactPoint = hit.pickedPoint;
  73787. if (!contactPoint) {
  73788. return null;
  73789. }
  73790. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  73791. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  73792. var directionToOrigin = contactPoint.normalize();
  73793. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  73794. directionToOrigin = directionToOrigin.negate();
  73795. }
  73796. // TODO: find a more physically based solution
  73797. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  73798. var forceX = directionToOrigin.x * this._strength / 8;
  73799. var forceY = directionToOrigin.y * this._updraftMultiplier;
  73800. var forceZ = directionToOrigin.z * this._strength / 8;
  73801. }
  73802. else {
  73803. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  73804. var forceY = this._originTop.y * this._updraftMultiplier;
  73805. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  73806. }
  73807. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  73808. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  73809. return { force: force, contactPoint: impostorObjectCenter };
  73810. };
  73811. PhysicsVortexEvent.prototype._tick = function () {
  73812. var _this = this;
  73813. this._physicsEngine.getImpostors().forEach(function (impostor) {
  73814. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  73815. if (!impostorForceAndContactPoint) {
  73816. return;
  73817. }
  73818. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  73819. });
  73820. };
  73821. /*** Helpers ***/
  73822. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  73823. if (!this._cylinder) {
  73824. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  73825. height: this._height,
  73826. diameter: this._radius * 2,
  73827. }, this._scene);
  73828. this._cylinder.isVisible = false;
  73829. }
  73830. };
  73831. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  73832. var impostorObject = impostor.object;
  73833. this._prepareCylinder();
  73834. this._cylinder.position = this._cylinderPosition;
  73835. return this._cylinder.intersectsMesh(impostorObject, true);
  73836. };
  73837. return PhysicsVortexEvent;
  73838. }());
  73839. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  73840. /***** Enums *****/
  73841. /**
  73842. * The strenght of the force in correspondence to the distance of the affected object
  73843. */
  73844. var PhysicsRadialImpulseFalloff;
  73845. (function (PhysicsRadialImpulseFalloff) {
  73846. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  73847. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  73848. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  73849. /**
  73850. * The strenght of the force in correspondence to the distance of the affected object
  73851. */
  73852. var PhysicsUpdraftMode;
  73853. (function (PhysicsUpdraftMode) {
  73854. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  73855. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  73856. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  73857. })(BABYLON || (BABYLON = {}));
  73858. //# sourceMappingURL=babylon.physicsHelper.js.map
  73859. var BABYLON;
  73860. (function (BABYLON) {
  73861. var CannonJSPlugin = /** @class */ (function () {
  73862. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  73863. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  73864. if (iterations === void 0) { iterations = 10; }
  73865. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  73866. this.name = "CannonJSPlugin";
  73867. this._physicsMaterials = new Array();
  73868. this._fixedTimeStep = 1 / 60;
  73869. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  73870. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  73871. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  73872. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  73873. this._tmpPosition = BABYLON.Vector3.Zero();
  73874. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  73875. this._tmpUnityRotation = new BABYLON.Quaternion();
  73876. if (!this.isSupported()) {
  73877. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  73878. return;
  73879. }
  73880. this._extendNamespace();
  73881. this.world = new this.BJSCANNON.World();
  73882. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  73883. this.world.solver.iterations = iterations;
  73884. }
  73885. CannonJSPlugin.prototype.setGravity = function (gravity) {
  73886. this.world.gravity.copy(gravity);
  73887. };
  73888. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  73889. this._fixedTimeStep = timeStep;
  73890. };
  73891. CannonJSPlugin.prototype.getTimeStep = function () {
  73892. return this._fixedTimeStep;
  73893. };
  73894. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  73895. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  73896. };
  73897. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  73898. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  73899. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  73900. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  73901. };
  73902. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  73903. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  73904. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  73905. impostor.physicsBody.applyForce(impulse, worldPoint);
  73906. };
  73907. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  73908. //parent-child relationship. Does this impostor has a parent impostor?
  73909. if (impostor.parent) {
  73910. if (impostor.physicsBody) {
  73911. this.removePhysicsBody(impostor);
  73912. //TODO is that needed?
  73913. impostor.forceUpdate();
  73914. }
  73915. return;
  73916. }
  73917. //should a new body be created for this impostor?
  73918. if (impostor.isBodyInitRequired()) {
  73919. var shape = this._createShape(impostor);
  73920. //unregister events, if body is being changed
  73921. var oldBody = impostor.physicsBody;
  73922. if (oldBody) {
  73923. this.removePhysicsBody(impostor);
  73924. }
  73925. //create the body and material
  73926. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  73927. var bodyCreationObject = {
  73928. mass: impostor.getParam("mass"),
  73929. material: material
  73930. };
  73931. // A simple extend, in case native options were used.
  73932. var nativeOptions = impostor.getParam("nativeOptions");
  73933. for (var key in nativeOptions) {
  73934. if (nativeOptions.hasOwnProperty(key)) {
  73935. bodyCreationObject[key] = nativeOptions[key];
  73936. }
  73937. }
  73938. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  73939. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  73940. this.world.addEventListener("preStep", impostor.beforeStep);
  73941. this.world.addEventListener("postStep", impostor.afterStep);
  73942. impostor.physicsBody.addShape(shape);
  73943. this.world.add(impostor.physicsBody);
  73944. //try to keep the body moving in the right direction by taking old properties.
  73945. //Should be tested!
  73946. if (oldBody) {
  73947. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  73948. impostor.physicsBody[param].copy(oldBody[param]);
  73949. });
  73950. }
  73951. this._processChildMeshes(impostor);
  73952. }
  73953. //now update the body's transformation
  73954. this._updatePhysicsBodyTransformation(impostor);
  73955. };
  73956. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  73957. var _this = this;
  73958. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  73959. var currentRotation = mainImpostor.object.rotationQuaternion;
  73960. if (meshChildren.length) {
  73961. var processMesh = function (localPosition, mesh) {
  73962. if (!currentRotation || !mesh.rotationQuaternion) {
  73963. return;
  73964. }
  73965. var childImpostor = mesh.getPhysicsImpostor();
  73966. if (childImpostor) {
  73967. var parent = childImpostor.parent;
  73968. if (parent !== mainImpostor) {
  73969. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  73970. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  73971. if (childImpostor.physicsBody) {
  73972. _this.removePhysicsBody(childImpostor);
  73973. childImpostor.physicsBody = null;
  73974. }
  73975. childImpostor.parent = mainImpostor;
  73976. childImpostor.resetUpdateFlags();
  73977. 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));
  73978. //Add the mass of the children.
  73979. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  73980. }
  73981. }
  73982. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  73983. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  73984. };
  73985. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  73986. }
  73987. };
  73988. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  73989. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  73990. this.world.removeEventListener("preStep", impostor.beforeStep);
  73991. this.world.removeEventListener("postStep", impostor.afterStep);
  73992. this.world.remove(impostor.physicsBody);
  73993. };
  73994. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  73995. var mainBody = impostorJoint.mainImpostor.physicsBody;
  73996. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  73997. if (!mainBody || !connectedBody) {
  73998. return;
  73999. }
  74000. var constraint;
  74001. var jointData = impostorJoint.joint.jointData;
  74002. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  74003. var constraintData = {
  74004. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  74005. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  74006. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  74007. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  74008. maxForce: jointData.nativeParams.maxForce,
  74009. collideConnected: !!jointData.collision
  74010. };
  74011. switch (impostorJoint.joint.type) {
  74012. case BABYLON.PhysicsJoint.HingeJoint:
  74013. case BABYLON.PhysicsJoint.Hinge2Joint:
  74014. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  74015. break;
  74016. case BABYLON.PhysicsJoint.DistanceJoint:
  74017. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  74018. break;
  74019. case BABYLON.PhysicsJoint.SpringJoint:
  74020. var springData = jointData;
  74021. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  74022. restLength: springData.length,
  74023. stiffness: springData.stiffness,
  74024. damping: springData.damping,
  74025. localAnchorA: constraintData.pivotA,
  74026. localAnchorB: constraintData.pivotB
  74027. });
  74028. break;
  74029. case BABYLON.PhysicsJoint.LockJoint:
  74030. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  74031. break;
  74032. case BABYLON.PhysicsJoint.PointToPointJoint:
  74033. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  74034. default:
  74035. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  74036. break;
  74037. }
  74038. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  74039. constraint.collideConnected = !!jointData.collision;
  74040. impostorJoint.joint.physicsJoint = constraint;
  74041. //don't add spring as constraint, as it is not one.
  74042. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  74043. this.world.addConstraint(constraint);
  74044. }
  74045. else {
  74046. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  74047. constraint.applyForce();
  74048. });
  74049. }
  74050. };
  74051. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  74052. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  74053. };
  74054. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  74055. var index;
  74056. var mat;
  74057. for (index = 0; index < this._physicsMaterials.length; index++) {
  74058. mat = this._physicsMaterials[index];
  74059. if (mat.friction === friction && mat.restitution === restitution) {
  74060. return mat;
  74061. }
  74062. }
  74063. var currentMat = new this.BJSCANNON.Material(name);
  74064. currentMat.friction = friction;
  74065. currentMat.restitution = restitution;
  74066. this._physicsMaterials.push(currentMat);
  74067. return currentMat;
  74068. };
  74069. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  74070. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  74071. };
  74072. CannonJSPlugin.prototype._createShape = function (impostor) {
  74073. var object = impostor.object;
  74074. var returnValue;
  74075. var extendSize = impostor.getObjectExtendSize();
  74076. switch (impostor.type) {
  74077. case BABYLON.PhysicsImpostor.SphereImpostor:
  74078. var radiusX = extendSize.x;
  74079. var radiusY = extendSize.y;
  74080. var radiusZ = extendSize.z;
  74081. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  74082. break;
  74083. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  74084. case BABYLON.PhysicsImpostor.CylinderImpostor:
  74085. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  74086. break;
  74087. case BABYLON.PhysicsImpostor.BoxImpostor:
  74088. var box = extendSize.scale(0.5);
  74089. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  74090. break;
  74091. case BABYLON.PhysicsImpostor.PlaneImpostor:
  74092. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  74093. returnValue = new this.BJSCANNON.Plane();
  74094. break;
  74095. case BABYLON.PhysicsImpostor.MeshImpostor:
  74096. // should transform the vertex data to world coordinates!!
  74097. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  74098. var rawFaces = object.getIndices ? object.getIndices() : [];
  74099. if (!rawVerts)
  74100. return;
  74101. // get only scale! so the object could transform correctly.
  74102. var oldPosition = object.position.clone();
  74103. var oldRotation = object.rotation && object.rotation.clone();
  74104. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  74105. object.position.copyFromFloats(0, 0, 0);
  74106. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  74107. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  74108. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  74109. var transform = object.computeWorldMatrix(true);
  74110. // convert rawVerts to object space
  74111. var temp = new Array();
  74112. var index;
  74113. for (index = 0; index < rawVerts.length; index += 3) {
  74114. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  74115. }
  74116. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  74117. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  74118. //now set back the transformation!
  74119. object.position.copyFrom(oldPosition);
  74120. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  74121. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  74122. break;
  74123. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  74124. var oldPosition2 = object.position.clone();
  74125. var oldRotation2 = object.rotation && object.rotation.clone();
  74126. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  74127. object.position.copyFromFloats(0, 0, 0);
  74128. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  74129. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  74130. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  74131. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  74132. returnValue = this._createHeightmap(object);
  74133. object.position.copyFrom(oldPosition2);
  74134. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  74135. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  74136. object.computeWorldMatrix(true);
  74137. break;
  74138. case BABYLON.PhysicsImpostor.ParticleImpostor:
  74139. returnValue = new this.BJSCANNON.Particle();
  74140. break;
  74141. }
  74142. return returnValue;
  74143. };
  74144. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  74145. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  74146. var transform = object.computeWorldMatrix(true);
  74147. // convert rawVerts to object space
  74148. var temp = new Array();
  74149. var index;
  74150. for (index = 0; index < pos.length; index += 3) {
  74151. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  74152. }
  74153. pos = temp;
  74154. var matrix = new Array();
  74155. //For now pointDepth will not be used and will be automatically calculated.
  74156. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  74157. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  74158. var boundingInfo = object.getBoundingInfo();
  74159. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  74160. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  74161. var elementSize = dim * 2 / arraySize;
  74162. for (var i = 0; i < pos.length; i = i + 3) {
  74163. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  74164. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  74165. var y = -pos[i + 2] + minY;
  74166. if (!matrix[x]) {
  74167. matrix[x] = [];
  74168. }
  74169. if (!matrix[x][z]) {
  74170. matrix[x][z] = y;
  74171. }
  74172. matrix[x][z] = Math.max(y, matrix[x][z]);
  74173. }
  74174. for (var x = 0; x <= arraySize; ++x) {
  74175. if (!matrix[x]) {
  74176. var loc = 1;
  74177. while (!matrix[(x + loc) % arraySize]) {
  74178. loc++;
  74179. }
  74180. matrix[x] = matrix[(x + loc) % arraySize].slice();
  74181. //console.log("missing x", x);
  74182. }
  74183. for (var z = 0; z <= arraySize; ++z) {
  74184. if (!matrix[x][z]) {
  74185. var loc = 1;
  74186. var newValue;
  74187. while (newValue === undefined) {
  74188. newValue = matrix[x][(z + loc++) % arraySize];
  74189. }
  74190. matrix[x][z] = newValue;
  74191. }
  74192. }
  74193. }
  74194. var shape = new this.BJSCANNON.Heightfield(matrix, {
  74195. elementSize: elementSize
  74196. });
  74197. //For future reference, needed for body transformation
  74198. shape.minY = minY;
  74199. return shape;
  74200. };
  74201. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  74202. var object = impostor.object;
  74203. //make sure it is updated...
  74204. object.computeWorldMatrix && object.computeWorldMatrix(true);
  74205. // The delta between the mesh position and the mesh bounding box center
  74206. var bInfo = object.getBoundingInfo();
  74207. if (!bInfo)
  74208. return;
  74209. var center = impostor.getObjectCenter();
  74210. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  74211. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  74212. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  74213. this._tmpPosition.copyFrom(center);
  74214. var quaternion = object.rotationQuaternion;
  74215. if (!quaternion) {
  74216. return;
  74217. }
  74218. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  74219. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  74220. //-90 DEG in X, precalculated
  74221. quaternion = quaternion.multiply(this._minus90X);
  74222. //Invert! (Precalculated, 90 deg in X)
  74223. //No need to clone. this will never change.
  74224. impostor.setDeltaRotation(this._plus90X);
  74225. }
  74226. //If it is a heightfield, if should be centered.
  74227. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  74228. var mesh = object;
  74229. var boundingInfo = mesh.getBoundingInfo();
  74230. //calculate the correct body position:
  74231. var rotationQuaternion = mesh.rotationQuaternion;
  74232. mesh.rotationQuaternion = this._tmpUnityRotation;
  74233. mesh.computeWorldMatrix(true);
  74234. //get original center with no rotation
  74235. var c = center.clone();
  74236. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  74237. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  74238. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  74239. mesh.setPreTransformMatrix(p);
  74240. mesh.computeWorldMatrix(true);
  74241. //calculate the translation
  74242. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  74243. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  74244. //add it inverted to the delta
  74245. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  74246. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  74247. //rotation is back
  74248. mesh.rotationQuaternion = rotationQuaternion;
  74249. mesh.setPreTransformMatrix(oldPivot);
  74250. mesh.computeWorldMatrix(true);
  74251. }
  74252. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  74253. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  74254. //this._tmpPosition.copyFrom(object.position);
  74255. }
  74256. impostor.setDeltaPosition(this._tmpDeltaPosition);
  74257. //Now update the impostor object
  74258. impostor.physicsBody.position.copy(this._tmpPosition);
  74259. impostor.physicsBody.quaternion.copy(quaternion);
  74260. };
  74261. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  74262. impostor.object.position.copyFrom(impostor.physicsBody.position);
  74263. if (impostor.object.rotationQuaternion) {
  74264. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  74265. }
  74266. };
  74267. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  74268. impostor.physicsBody.position.copy(newPosition);
  74269. impostor.physicsBody.quaternion.copy(newRotation);
  74270. };
  74271. CannonJSPlugin.prototype.isSupported = function () {
  74272. return this.BJSCANNON !== undefined;
  74273. };
  74274. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  74275. impostor.physicsBody.velocity.copy(velocity);
  74276. };
  74277. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  74278. impostor.physicsBody.angularVelocity.copy(velocity);
  74279. };
  74280. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  74281. var v = impostor.physicsBody.velocity;
  74282. if (!v) {
  74283. return null;
  74284. }
  74285. return new BABYLON.Vector3(v.x, v.y, v.z);
  74286. };
  74287. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  74288. var v = impostor.physicsBody.angularVelocity;
  74289. if (!v) {
  74290. return null;
  74291. }
  74292. return new BABYLON.Vector3(v.x, v.y, v.z);
  74293. };
  74294. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  74295. impostor.physicsBody.mass = mass;
  74296. impostor.physicsBody.updateMassProperties();
  74297. };
  74298. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  74299. return impostor.physicsBody.mass;
  74300. };
  74301. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  74302. return impostor.physicsBody.material.friction;
  74303. };
  74304. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  74305. impostor.physicsBody.material.friction = friction;
  74306. };
  74307. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  74308. return impostor.physicsBody.material.restitution;
  74309. };
  74310. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  74311. impostor.physicsBody.material.restitution = restitution;
  74312. };
  74313. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  74314. impostor.physicsBody.sleep();
  74315. };
  74316. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  74317. impostor.physicsBody.wakeUp();
  74318. };
  74319. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  74320. joint.physicsJoint.distance = maxDistance;
  74321. };
  74322. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  74323. // if (!motorIndex) {
  74324. // joint.physicsJoint.enableMotor();
  74325. // }
  74326. // }
  74327. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  74328. // if (!motorIndex) {
  74329. // joint.physicsJoint.disableMotor();
  74330. // }
  74331. // }
  74332. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  74333. if (!motorIndex) {
  74334. joint.physicsJoint.enableMotor();
  74335. joint.physicsJoint.setMotorSpeed(speed);
  74336. if (maxForce) {
  74337. this.setLimit(joint, maxForce);
  74338. }
  74339. }
  74340. };
  74341. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  74342. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  74343. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  74344. };
  74345. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  74346. var body = impostor.physicsBody;
  74347. mesh.position.x = body.position.x;
  74348. mesh.position.y = body.position.y;
  74349. mesh.position.z = body.position.z;
  74350. if (mesh.rotationQuaternion) {
  74351. mesh.rotationQuaternion.x = body.quaternion.x;
  74352. mesh.rotationQuaternion.y = body.quaternion.y;
  74353. mesh.rotationQuaternion.z = body.quaternion.z;
  74354. mesh.rotationQuaternion.w = body.quaternion.w;
  74355. }
  74356. };
  74357. CannonJSPlugin.prototype.getRadius = function (impostor) {
  74358. var shape = impostor.physicsBody.shapes[0];
  74359. return shape.boundingSphereRadius;
  74360. };
  74361. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  74362. var shape = impostor.physicsBody.shapes[0];
  74363. result.x = shape.halfExtents.x * 2;
  74364. result.y = shape.halfExtents.y * 2;
  74365. result.z = shape.halfExtents.z * 2;
  74366. };
  74367. CannonJSPlugin.prototype.dispose = function () {
  74368. };
  74369. CannonJSPlugin.prototype._extendNamespace = function () {
  74370. //this will force cannon to execute at least one step when using interpolation
  74371. var step_tmp1 = new this.BJSCANNON.Vec3();
  74372. var Engine = this.BJSCANNON;
  74373. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  74374. maxSubSteps = maxSubSteps || 10;
  74375. timeSinceLastCalled = timeSinceLastCalled || 0;
  74376. if (timeSinceLastCalled === 0) {
  74377. this.internalStep(dt);
  74378. this.time += dt;
  74379. }
  74380. else {
  74381. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  74382. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  74383. var t0 = performance.now();
  74384. for (var i = 0; i !== internalSteps; i++) {
  74385. this.internalStep(dt);
  74386. if (performance.now() - t0 > dt * 1000) {
  74387. break;
  74388. }
  74389. }
  74390. this.time += timeSinceLastCalled;
  74391. var h = this.time % dt;
  74392. var h_div_dt = h / dt;
  74393. var interpvelo = step_tmp1;
  74394. var bodies = this.bodies;
  74395. for (var j = 0; j !== bodies.length; j++) {
  74396. var b = bodies[j];
  74397. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  74398. b.position.vsub(b.previousPosition, interpvelo);
  74399. interpvelo.scale(h_div_dt, interpvelo);
  74400. b.position.vadd(interpvelo, b.interpolatedPosition);
  74401. }
  74402. else {
  74403. b.interpolatedPosition.copy(b.position);
  74404. b.interpolatedQuaternion.copy(b.quaternion);
  74405. }
  74406. }
  74407. }
  74408. };
  74409. };
  74410. return CannonJSPlugin;
  74411. }());
  74412. BABYLON.CannonJSPlugin = CannonJSPlugin;
  74413. })(BABYLON || (BABYLON = {}));
  74414. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  74415. var BABYLON;
  74416. (function (BABYLON) {
  74417. var OimoJSPlugin = /** @class */ (function () {
  74418. function OimoJSPlugin(iterations) {
  74419. this.name = "OimoJSPlugin";
  74420. this._tmpImpostorsArray = [];
  74421. this._tmpPositionVector = BABYLON.Vector3.Zero();
  74422. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  74423. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  74424. this.world.worldscale(1);
  74425. this.world.clear();
  74426. //making sure no stats are calculated
  74427. this.world.isNoStat = true;
  74428. }
  74429. OimoJSPlugin.prototype.setGravity = function (gravity) {
  74430. this.world.gravity.copy(gravity);
  74431. };
  74432. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  74433. this.world.timeStep = timeStep;
  74434. };
  74435. OimoJSPlugin.prototype.getTimeStep = function () {
  74436. return this.world.timeStep;
  74437. };
  74438. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  74439. var _this = this;
  74440. impostors.forEach(function (impostor) {
  74441. impostor.beforeStep();
  74442. });
  74443. this.world.step();
  74444. impostors.forEach(function (impostor) {
  74445. impostor.afterStep();
  74446. //update the ordered impostors array
  74447. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  74448. });
  74449. //check for collisions
  74450. var contact = this.world.contacts;
  74451. while (contact !== null) {
  74452. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  74453. contact = contact.next;
  74454. continue;
  74455. }
  74456. //is this body colliding with any other? get the impostor
  74457. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  74458. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  74459. if (!mainImpostor || !collidingImpostor) {
  74460. contact = contact.next;
  74461. continue;
  74462. }
  74463. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  74464. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  74465. contact = contact.next;
  74466. }
  74467. };
  74468. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  74469. var mass = impostor.physicsBody.massInfo.mass;
  74470. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  74471. };
  74472. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  74473. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  74474. this.applyImpulse(impostor, force, contactPoint);
  74475. };
  74476. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  74477. var _this = this;
  74478. //parent-child relationship. Does this impostor has a parent impostor?
  74479. if (impostor.parent) {
  74480. if (impostor.physicsBody) {
  74481. this.removePhysicsBody(impostor);
  74482. //TODO is that needed?
  74483. impostor.forceUpdate();
  74484. }
  74485. return;
  74486. }
  74487. if (impostor.isBodyInitRequired()) {
  74488. var bodyConfig = {
  74489. name: impostor.uniqueId,
  74490. //Oimo must have mass, also for static objects.
  74491. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  74492. size: [],
  74493. type: [],
  74494. pos: [],
  74495. rot: [],
  74496. move: impostor.getParam("mass") !== 0,
  74497. //Supporting older versions of Oimo
  74498. world: this.world
  74499. };
  74500. var impostors = [impostor];
  74501. var addToArray = function (parent) {
  74502. if (!parent.getChildMeshes)
  74503. return;
  74504. parent.getChildMeshes().forEach(function (m) {
  74505. if (m.physicsImpostor) {
  74506. impostors.push(m.physicsImpostor);
  74507. //m.physicsImpostor._init();
  74508. }
  74509. });
  74510. };
  74511. addToArray(impostor.object);
  74512. var checkWithEpsilon_1 = function (value) {
  74513. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  74514. };
  74515. impostors.forEach(function (i) {
  74516. if (!impostor.object.rotationQuaternion) {
  74517. return;
  74518. }
  74519. //get the correct bounding box
  74520. var oldQuaternion = i.object.rotationQuaternion;
  74521. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  74522. x: impostor.object.rotationQuaternion.x,
  74523. y: impostor.object.rotationQuaternion.y,
  74524. z: impostor.object.rotationQuaternion.z,
  74525. s: impostor.object.rotationQuaternion.w
  74526. });
  74527. var extendSize = i.getObjectExtendSize();
  74528. if (i === impostor) {
  74529. var center = impostor.getObjectCenter();
  74530. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  74531. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  74532. //Can also use Array.prototype.push.apply
  74533. bodyConfig.pos.push(center.x);
  74534. bodyConfig.pos.push(center.y);
  74535. bodyConfig.pos.push(center.z);
  74536. //tmp solution
  74537. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  74538. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  74539. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  74540. }
  74541. else {
  74542. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  74543. bodyConfig.pos.push(localPosition.x);
  74544. bodyConfig.pos.push(localPosition.y);
  74545. bodyConfig.pos.push(localPosition.z);
  74546. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  74547. bodyConfig.rot.push(0);
  74548. bodyConfig.rot.push(0);
  74549. bodyConfig.rot.push(0);
  74550. }
  74551. // register mesh
  74552. switch (i.type) {
  74553. case BABYLON.PhysicsImpostor.ParticleImpostor:
  74554. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  74555. case BABYLON.PhysicsImpostor.SphereImpostor:
  74556. var radiusX = extendSize.x;
  74557. var radiusY = extendSize.y;
  74558. var radiusZ = extendSize.z;
  74559. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  74560. bodyConfig.type.push('sphere');
  74561. //due to the way oimo works with compounds, add 3 times
  74562. bodyConfig.size.push(size);
  74563. bodyConfig.size.push(size);
  74564. bodyConfig.size.push(size);
  74565. break;
  74566. case BABYLON.PhysicsImpostor.CylinderImpostor:
  74567. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  74568. var sizeY = checkWithEpsilon_1(extendSize.y);
  74569. bodyConfig.type.push('cylinder');
  74570. bodyConfig.size.push(sizeX);
  74571. bodyConfig.size.push(sizeY);
  74572. //due to the way oimo works with compounds, add one more value.
  74573. bodyConfig.size.push(sizeY);
  74574. break;
  74575. case BABYLON.PhysicsImpostor.PlaneImpostor:
  74576. case BABYLON.PhysicsImpostor.BoxImpostor:
  74577. default:
  74578. var sizeX = checkWithEpsilon_1(extendSize.x);
  74579. var sizeY = checkWithEpsilon_1(extendSize.y);
  74580. var sizeZ = checkWithEpsilon_1(extendSize.z);
  74581. bodyConfig.type.push('box');
  74582. bodyConfig.size.push(sizeX);
  74583. bodyConfig.size.push(sizeY);
  74584. bodyConfig.size.push(sizeZ);
  74585. break;
  74586. }
  74587. //actually not needed, but hey...
  74588. i.object.rotationQuaternion = oldQuaternion;
  74589. });
  74590. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  74591. }
  74592. else {
  74593. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  74594. }
  74595. impostor.setDeltaPosition(this._tmpPositionVector);
  74596. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  74597. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  74598. };
  74599. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  74600. //impostor.physicsBody.dispose();
  74601. //Same as : (older oimo versions)
  74602. this.world.removeRigidBody(impostor.physicsBody);
  74603. };
  74604. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  74605. var mainBody = impostorJoint.mainImpostor.physicsBody;
  74606. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  74607. if (!mainBody || !connectedBody) {
  74608. return;
  74609. }
  74610. var jointData = impostorJoint.joint.jointData;
  74611. var options = jointData.nativeParams || {};
  74612. var type;
  74613. var nativeJointData = {
  74614. body1: mainBody,
  74615. body2: connectedBody,
  74616. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  74617. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  74618. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  74619. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  74620. min: options.min,
  74621. max: options.max,
  74622. collision: options.collision || jointData.collision,
  74623. spring: options.spring,
  74624. //supporting older version of Oimo
  74625. world: this.world
  74626. };
  74627. switch (impostorJoint.joint.type) {
  74628. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  74629. type = "jointBall";
  74630. break;
  74631. case BABYLON.PhysicsJoint.SpringJoint:
  74632. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  74633. var springData = jointData;
  74634. nativeJointData.min = springData.length || nativeJointData.min;
  74635. //Max should also be set, just make sure it is at least min
  74636. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  74637. case BABYLON.PhysicsJoint.DistanceJoint:
  74638. type = "jointDistance";
  74639. nativeJointData.max = jointData.maxDistance;
  74640. break;
  74641. case BABYLON.PhysicsJoint.PrismaticJoint:
  74642. type = "jointPrisme";
  74643. break;
  74644. case BABYLON.PhysicsJoint.SliderJoint:
  74645. type = "jointSlide";
  74646. break;
  74647. case BABYLON.PhysicsJoint.WheelJoint:
  74648. type = "jointWheel";
  74649. break;
  74650. case BABYLON.PhysicsJoint.HingeJoint:
  74651. default:
  74652. type = "jointHinge";
  74653. break;
  74654. }
  74655. nativeJointData.type = type;
  74656. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  74657. };
  74658. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  74659. //Bug in Oimo prevents us from disposing a joint in the playground
  74660. //joint.joint.physicsJoint.dispose();
  74661. //So we will bruteforce it!
  74662. try {
  74663. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  74664. }
  74665. catch (e) {
  74666. BABYLON.Tools.Warn(e);
  74667. }
  74668. };
  74669. OimoJSPlugin.prototype.isSupported = function () {
  74670. return this.BJSOIMO !== undefined;
  74671. };
  74672. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  74673. if (!impostor.physicsBody.sleeping) {
  74674. //TODO check that
  74675. if (impostor.physicsBody.shapes.next) {
  74676. var parentShape = this._getLastShape(impostor.physicsBody);
  74677. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  74678. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  74679. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  74680. }
  74681. else {
  74682. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  74683. }
  74684. if (impostor.object.rotationQuaternion) {
  74685. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  74686. impostor.object.rotationQuaternion.normalize();
  74687. }
  74688. }
  74689. };
  74690. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  74691. var body = impostor.physicsBody;
  74692. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  74693. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  74694. body.syncShapes();
  74695. body.awake();
  74696. };
  74697. OimoJSPlugin.prototype._getLastShape = function (body) {
  74698. var lastShape = body.shapes;
  74699. while (lastShape.next) {
  74700. lastShape = lastShape.next;
  74701. }
  74702. return lastShape;
  74703. };
  74704. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  74705. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  74706. };
  74707. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  74708. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  74709. };
  74710. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  74711. var v = impostor.physicsBody.linearVelocity;
  74712. if (!v) {
  74713. return null;
  74714. }
  74715. return new BABYLON.Vector3(v.x, v.y, v.z);
  74716. };
  74717. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  74718. var v = impostor.physicsBody.angularVelocity;
  74719. if (!v) {
  74720. return null;
  74721. }
  74722. return new BABYLON.Vector3(v.x, v.y, v.z);
  74723. };
  74724. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  74725. var staticBody = mass === 0;
  74726. //this will actually set the body's density and not its mass.
  74727. //But this is how oimo treats the mass variable.
  74728. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  74729. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  74730. };
  74731. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  74732. return impostor.physicsBody.shapes.density;
  74733. };
  74734. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  74735. return impostor.physicsBody.shapes.friction;
  74736. };
  74737. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  74738. impostor.physicsBody.shapes.friction = friction;
  74739. };
  74740. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  74741. return impostor.physicsBody.shapes.restitution;
  74742. };
  74743. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  74744. impostor.physicsBody.shapes.restitution = restitution;
  74745. };
  74746. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  74747. impostor.physicsBody.sleep();
  74748. };
  74749. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  74750. impostor.physicsBody.awake();
  74751. };
  74752. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  74753. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  74754. if (minDistance !== void 0) {
  74755. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  74756. }
  74757. };
  74758. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  74759. //TODO separate rotational and transational motors.
  74760. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  74761. if (motor) {
  74762. motor.setMotor(speed, maxForce);
  74763. }
  74764. };
  74765. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  74766. //TODO separate rotational and transational motors.
  74767. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  74768. if (motor) {
  74769. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  74770. }
  74771. };
  74772. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  74773. var body = impostor.physicsBody;
  74774. mesh.position.x = body.position.x;
  74775. mesh.position.y = body.position.y;
  74776. mesh.position.z = body.position.z;
  74777. if (mesh.rotationQuaternion) {
  74778. mesh.rotationQuaternion.x = body.orientation.x;
  74779. mesh.rotationQuaternion.y = body.orientation.y;
  74780. mesh.rotationQuaternion.z = body.orientation.z;
  74781. mesh.rotationQuaternion.w = body.orientation.s;
  74782. }
  74783. };
  74784. OimoJSPlugin.prototype.getRadius = function (impostor) {
  74785. return impostor.physicsBody.shapes.radius;
  74786. };
  74787. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  74788. var shape = impostor.physicsBody.shapes;
  74789. result.x = shape.halfWidth * 2;
  74790. result.y = shape.halfHeight * 2;
  74791. result.z = shape.halfDepth * 2;
  74792. };
  74793. OimoJSPlugin.prototype.dispose = function () {
  74794. this.world.clear();
  74795. };
  74796. return OimoJSPlugin;
  74797. }());
  74798. BABYLON.OimoJSPlugin = OimoJSPlugin;
  74799. })(BABYLON || (BABYLON = {}));
  74800. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  74801. var BABYLON;
  74802. (function (BABYLON) {
  74803. /*
  74804. * Based on jsTGALoader - Javascript loader for TGA file
  74805. * By Vincent Thibault
  74806. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  74807. */
  74808. var TGATools = /** @class */ (function () {
  74809. function TGATools() {
  74810. }
  74811. TGATools.GetTGAHeader = function (data) {
  74812. var offset = 0;
  74813. var header = {
  74814. id_length: data[offset++],
  74815. colormap_type: data[offset++],
  74816. image_type: data[offset++],
  74817. colormap_index: data[offset++] | data[offset++] << 8,
  74818. colormap_length: data[offset++] | data[offset++] << 8,
  74819. colormap_size: data[offset++],
  74820. origin: [
  74821. data[offset++] | data[offset++] << 8,
  74822. data[offset++] | data[offset++] << 8
  74823. ],
  74824. width: data[offset++] | data[offset++] << 8,
  74825. height: data[offset++] | data[offset++] << 8,
  74826. pixel_size: data[offset++],
  74827. flags: data[offset++]
  74828. };
  74829. return header;
  74830. };
  74831. TGATools.UploadContent = function (gl, data) {
  74832. // Not enough data to contain header ?
  74833. if (data.length < 19) {
  74834. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  74835. return;
  74836. }
  74837. // Read Header
  74838. var offset = 18;
  74839. var header = TGATools.GetTGAHeader(data);
  74840. // Assume it's a valid Targa file.
  74841. if (header.id_length + offset > data.length) {
  74842. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  74843. return;
  74844. }
  74845. // Skip not needed data
  74846. offset += header.id_length;
  74847. var use_rle = false;
  74848. var use_pal = false;
  74849. var use_grey = false;
  74850. // Get some informations.
  74851. switch (header.image_type) {
  74852. case TGATools._TYPE_RLE_INDEXED:
  74853. use_rle = true;
  74854. case TGATools._TYPE_INDEXED:
  74855. use_pal = true;
  74856. break;
  74857. case TGATools._TYPE_RLE_RGB:
  74858. use_rle = true;
  74859. case TGATools._TYPE_RGB:
  74860. // use_rgb = true;
  74861. break;
  74862. case TGATools._TYPE_RLE_GREY:
  74863. use_rle = true;
  74864. case TGATools._TYPE_GREY:
  74865. use_grey = true;
  74866. break;
  74867. }
  74868. var pixel_data;
  74869. // var numAlphaBits = header.flags & 0xf;
  74870. var pixel_size = header.pixel_size >> 3;
  74871. var pixel_total = header.width * header.height * pixel_size;
  74872. // Read palettes
  74873. var palettes;
  74874. if (use_pal) {
  74875. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  74876. }
  74877. // Read LRE
  74878. if (use_rle) {
  74879. pixel_data = new Uint8Array(pixel_total);
  74880. var c, count, i;
  74881. var localOffset = 0;
  74882. var pixels = new Uint8Array(pixel_size);
  74883. while (offset < pixel_total && localOffset < pixel_total) {
  74884. c = data[offset++];
  74885. count = (c & 0x7f) + 1;
  74886. // RLE pixels
  74887. if (c & 0x80) {
  74888. // Bind pixel tmp array
  74889. for (i = 0; i < pixel_size; ++i) {
  74890. pixels[i] = data[offset++];
  74891. }
  74892. // Copy pixel array
  74893. for (i = 0; i < count; ++i) {
  74894. pixel_data.set(pixels, localOffset + i * pixel_size);
  74895. }
  74896. localOffset += pixel_size * count;
  74897. }
  74898. else {
  74899. count *= pixel_size;
  74900. for (i = 0; i < count; ++i) {
  74901. pixel_data[localOffset + i] = data[offset++];
  74902. }
  74903. localOffset += count;
  74904. }
  74905. }
  74906. }
  74907. else {
  74908. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  74909. }
  74910. // Load to texture
  74911. var x_start, y_start, x_step, y_step, y_end, x_end;
  74912. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  74913. default:
  74914. case TGATools._ORIGIN_UL:
  74915. x_start = 0;
  74916. x_step = 1;
  74917. x_end = header.width;
  74918. y_start = 0;
  74919. y_step = 1;
  74920. y_end = header.height;
  74921. break;
  74922. case TGATools._ORIGIN_BL:
  74923. x_start = 0;
  74924. x_step = 1;
  74925. x_end = header.width;
  74926. y_start = header.height - 1;
  74927. y_step = -1;
  74928. y_end = -1;
  74929. break;
  74930. case TGATools._ORIGIN_UR:
  74931. x_start = header.width - 1;
  74932. x_step = -1;
  74933. x_end = -1;
  74934. y_start = 0;
  74935. y_step = 1;
  74936. y_end = header.height;
  74937. break;
  74938. case TGATools._ORIGIN_BR:
  74939. x_start = header.width - 1;
  74940. x_step = -1;
  74941. x_end = -1;
  74942. y_start = header.height - 1;
  74943. y_step = -1;
  74944. y_end = -1;
  74945. break;
  74946. }
  74947. // Load the specify method
  74948. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  74949. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  74950. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  74951. };
  74952. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  74953. var image = pixel_data, colormap = palettes;
  74954. var width = header.width, height = header.height;
  74955. var color, i = 0, x, y;
  74956. var imageData = new Uint8Array(width * height * 4);
  74957. for (y = y_start; y !== y_end; y += y_step) {
  74958. for (x = x_start; x !== x_end; x += x_step, i++) {
  74959. color = image[i];
  74960. imageData[(x + width * y) * 4 + 3] = 255;
  74961. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  74962. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  74963. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  74964. }
  74965. }
  74966. return imageData;
  74967. };
  74968. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  74969. var image = pixel_data;
  74970. var width = header.width, height = header.height;
  74971. var color, i = 0, x, y;
  74972. var imageData = new Uint8Array(width * height * 4);
  74973. for (y = y_start; y !== y_end; y += y_step) {
  74974. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  74975. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  74976. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  74977. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  74978. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  74979. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  74980. }
  74981. }
  74982. return imageData;
  74983. };
  74984. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  74985. var image = pixel_data;
  74986. var width = header.width, height = header.height;
  74987. var i = 0, x, y;
  74988. var imageData = new Uint8Array(width * height * 4);
  74989. for (y = y_start; y !== y_end; y += y_step) {
  74990. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  74991. imageData[(x + width * y) * 4 + 3] = 255;
  74992. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  74993. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  74994. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  74995. }
  74996. }
  74997. return imageData;
  74998. };
  74999. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75000. var image = pixel_data;
  75001. var width = header.width, height = header.height;
  75002. var i = 0, x, y;
  75003. var imageData = new Uint8Array(width * height * 4);
  75004. for (y = y_start; y !== y_end; y += y_step) {
  75005. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  75006. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75007. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  75008. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  75009. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  75010. }
  75011. }
  75012. return imageData;
  75013. };
  75014. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75015. var image = pixel_data;
  75016. var width = header.width, height = header.height;
  75017. var color, i = 0, x, y;
  75018. var imageData = new Uint8Array(width * height * 4);
  75019. for (y = y_start; y !== y_end; y += y_step) {
  75020. for (x = x_start; x !== x_end; x += x_step, i++) {
  75021. color = image[i];
  75022. imageData[(x + width * y) * 4 + 0] = color;
  75023. imageData[(x + width * y) * 4 + 1] = color;
  75024. imageData[(x + width * y) * 4 + 2] = color;
  75025. imageData[(x + width * y) * 4 + 3] = 255;
  75026. }
  75027. }
  75028. return imageData;
  75029. };
  75030. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75031. var image = pixel_data;
  75032. var width = header.width, height = header.height;
  75033. var i = 0, x, y;
  75034. var imageData = new Uint8Array(width * height * 4);
  75035. for (y = y_start; y !== y_end; y += y_step) {
  75036. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  75037. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  75038. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  75039. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75040. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  75041. }
  75042. }
  75043. return imageData;
  75044. };
  75045. //private static _TYPE_NO_DATA = 0;
  75046. TGATools._TYPE_INDEXED = 1;
  75047. TGATools._TYPE_RGB = 2;
  75048. TGATools._TYPE_GREY = 3;
  75049. TGATools._TYPE_RLE_INDEXED = 9;
  75050. TGATools._TYPE_RLE_RGB = 10;
  75051. TGATools._TYPE_RLE_GREY = 11;
  75052. TGATools._ORIGIN_MASK = 0x30;
  75053. TGATools._ORIGIN_SHIFT = 0x04;
  75054. TGATools._ORIGIN_BL = 0x00;
  75055. TGATools._ORIGIN_BR = 0x01;
  75056. TGATools._ORIGIN_UL = 0x02;
  75057. TGATools._ORIGIN_UR = 0x03;
  75058. return TGATools;
  75059. }());
  75060. BABYLON.TGATools = TGATools;
  75061. })(BABYLON || (BABYLON = {}));
  75062. //# sourceMappingURL=babylon.tga.js.map
  75063. var BABYLON;
  75064. (function (BABYLON) {
  75065. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  75066. // All values and structures referenced from:
  75067. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  75068. var DDS_MAGIC = 0x20534444;
  75069. var
  75070. //DDSD_CAPS = 0x1,
  75071. //DDSD_HEIGHT = 0x2,
  75072. //DDSD_WIDTH = 0x4,
  75073. //DDSD_PITCH = 0x8,
  75074. //DDSD_PIXELFORMAT = 0x1000,
  75075. DDSD_MIPMAPCOUNT = 0x20000;
  75076. //DDSD_LINEARSIZE = 0x80000,
  75077. //DDSD_DEPTH = 0x800000;
  75078. // var DDSCAPS_COMPLEX = 0x8,
  75079. // DDSCAPS_MIPMAP = 0x400000,
  75080. // DDSCAPS_TEXTURE = 0x1000;
  75081. var DDSCAPS2_CUBEMAP = 0x200;
  75082. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  75083. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  75084. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  75085. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  75086. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  75087. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  75088. // DDSCAPS2_VOLUME = 0x200000;
  75089. var
  75090. //DDPF_ALPHAPIXELS = 0x1,
  75091. //DDPF_ALPHA = 0x2,
  75092. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  75093. //DDPF_YUV = 0x200,
  75094. DDPF_LUMINANCE = 0x20000;
  75095. function FourCCToInt32(value) {
  75096. return value.charCodeAt(0) +
  75097. (value.charCodeAt(1) << 8) +
  75098. (value.charCodeAt(2) << 16) +
  75099. (value.charCodeAt(3) << 24);
  75100. }
  75101. function Int32ToFourCC(value) {
  75102. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  75103. }
  75104. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  75105. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  75106. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  75107. var FOURCC_DX10 = FourCCToInt32("DX10");
  75108. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  75109. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  75110. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  75111. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  75112. var headerLengthInt = 31; // The header length in 32 bit ints
  75113. // Offsets into the header array
  75114. var off_magic = 0;
  75115. var off_size = 1;
  75116. var off_flags = 2;
  75117. var off_height = 3;
  75118. var off_width = 4;
  75119. var off_mipmapCount = 7;
  75120. var off_pfFlags = 20;
  75121. var off_pfFourCC = 21;
  75122. var off_RGBbpp = 22;
  75123. var off_RMask = 23;
  75124. var off_GMask = 24;
  75125. var off_BMask = 25;
  75126. var off_AMask = 26;
  75127. // var off_caps1 = 27;
  75128. var off_caps2 = 28;
  75129. // var off_caps3 = 29;
  75130. // var off_caps4 = 30;
  75131. var off_dxgiFormat = 32;
  75132. ;
  75133. var DDSTools = /** @class */ (function () {
  75134. function DDSTools() {
  75135. }
  75136. DDSTools.GetDDSInfo = function (arrayBuffer) {
  75137. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  75138. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  75139. var mipmapCount = 1;
  75140. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  75141. mipmapCount = Math.max(1, header[off_mipmapCount]);
  75142. }
  75143. var fourCC = header[off_pfFourCC];
  75144. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  75145. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75146. switch (fourCC) {
  75147. case FOURCC_D3DFMT_R16G16B16A16F:
  75148. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75149. break;
  75150. case FOURCC_D3DFMT_R32G32B32A32F:
  75151. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75152. break;
  75153. case FOURCC_DX10:
  75154. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  75155. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75156. break;
  75157. }
  75158. }
  75159. return {
  75160. width: header[off_width],
  75161. height: header[off_height],
  75162. mipmapCount: mipmapCount,
  75163. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  75164. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  75165. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  75166. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  75167. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  75168. dxgiFormat: dxgiFormat,
  75169. textureType: textureType
  75170. };
  75171. };
  75172. DDSTools._ToHalfFloat = function (value) {
  75173. if (!DDSTools._FloatView) {
  75174. DDSTools._FloatView = new Float32Array(1);
  75175. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  75176. }
  75177. DDSTools._FloatView[0] = value;
  75178. var x = DDSTools._Int32View[0];
  75179. var bits = (x >> 16) & 0x8000; /* Get the sign */
  75180. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  75181. var e = (x >> 23) & 0xff; /* Using int is faster here */
  75182. /* If zero, or denormal, or exponent underflows too much for a denormal
  75183. * half, return signed zero. */
  75184. if (e < 103) {
  75185. return bits;
  75186. }
  75187. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  75188. if (e > 142) {
  75189. bits |= 0x7c00;
  75190. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  75191. * not Inf, so make sure we set one mantissa bit too. */
  75192. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  75193. return bits;
  75194. }
  75195. /* If exponent underflows but not too much, return a denormal */
  75196. if (e < 113) {
  75197. m |= 0x0800;
  75198. /* Extra rounding may overflow and set mantissa to 0 and exponent
  75199. * to 1, which is OK. */
  75200. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  75201. return bits;
  75202. }
  75203. bits |= ((e - 112) << 10) | (m >> 1);
  75204. bits += m & 1;
  75205. return bits;
  75206. };
  75207. DDSTools._FromHalfFloat = function (value) {
  75208. var s = (value & 0x8000) >> 15;
  75209. var e = (value & 0x7C00) >> 10;
  75210. var f = value & 0x03FF;
  75211. if (e === 0) {
  75212. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  75213. }
  75214. else if (e == 0x1F) {
  75215. return f ? NaN : ((s ? -1 : 1) * Infinity);
  75216. }
  75217. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  75218. };
  75219. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75220. var destArray = new Float32Array(dataLength);
  75221. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  75222. var index = 0;
  75223. for (var y = 0; y < height; y++) {
  75224. for (var x = 0; x < width; x++) {
  75225. var srcPos = (x + y * width) * 4;
  75226. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  75227. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  75228. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  75229. if (DDSTools.StoreLODInAlphaChannel) {
  75230. destArray[index + 3] = lod;
  75231. }
  75232. else {
  75233. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  75234. }
  75235. index += 4;
  75236. }
  75237. }
  75238. return destArray;
  75239. };
  75240. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75241. if (DDSTools.StoreLODInAlphaChannel) {
  75242. var destArray = new Uint16Array(dataLength);
  75243. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  75244. var index = 0;
  75245. for (var y = 0; y < height; y++) {
  75246. for (var x = 0; x < width; x++) {
  75247. var srcPos = (x + y * width) * 4;
  75248. destArray[index] = srcData[srcPos];
  75249. destArray[index + 1] = srcData[srcPos + 1];
  75250. destArray[index + 2] = srcData[srcPos + 2];
  75251. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  75252. index += 4;
  75253. }
  75254. }
  75255. return destArray;
  75256. }
  75257. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  75258. };
  75259. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75260. if (DDSTools.StoreLODInAlphaChannel) {
  75261. var destArray = new Float32Array(dataLength);
  75262. var srcData = new Float32Array(arrayBuffer, dataOffset);
  75263. var index = 0;
  75264. for (var y = 0; y < height; y++) {
  75265. for (var x = 0; x < width; x++) {
  75266. var srcPos = (x + y * width) * 4;
  75267. destArray[index] = srcData[srcPos];
  75268. destArray[index + 1] = srcData[srcPos + 1];
  75269. destArray[index + 2] = srcData[srcPos + 2];
  75270. destArray[index + 3] = lod;
  75271. index += 4;
  75272. }
  75273. }
  75274. return destArray;
  75275. }
  75276. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  75277. };
  75278. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75279. var destArray = new Uint8Array(dataLength);
  75280. var srcData = new Float32Array(arrayBuffer, dataOffset);
  75281. var index = 0;
  75282. for (var y = 0; y < height; y++) {
  75283. for (var x = 0; x < width; x++) {
  75284. var srcPos = (x + y * width) * 4;
  75285. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  75286. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  75287. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  75288. if (DDSTools.StoreLODInAlphaChannel) {
  75289. destArray[index + 3] = lod;
  75290. }
  75291. else {
  75292. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  75293. }
  75294. index += 4;
  75295. }
  75296. }
  75297. return destArray;
  75298. };
  75299. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75300. var destArray = new Uint8Array(dataLength);
  75301. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  75302. var index = 0;
  75303. for (var y = 0; y < height; y++) {
  75304. for (var x = 0; x < width; x++) {
  75305. var srcPos = (x + y * width) * 4;
  75306. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  75307. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  75308. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  75309. if (DDSTools.StoreLODInAlphaChannel) {
  75310. destArray[index + 3] = lod;
  75311. }
  75312. else {
  75313. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  75314. }
  75315. index += 4;
  75316. }
  75317. }
  75318. return destArray;
  75319. };
  75320. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  75321. var byteArray = new Uint8Array(dataLength);
  75322. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  75323. var index = 0;
  75324. for (var y = 0; y < height; y++) {
  75325. for (var x = 0; x < width; x++) {
  75326. var srcPos = (x + y * width) * 4;
  75327. byteArray[index] = srcData[srcPos + rOffset];
  75328. byteArray[index + 1] = srcData[srcPos + gOffset];
  75329. byteArray[index + 2] = srcData[srcPos + bOffset];
  75330. byteArray[index + 3] = srcData[srcPos + aOffset];
  75331. index += 4;
  75332. }
  75333. }
  75334. return byteArray;
  75335. };
  75336. DDSTools._ExtractLongWordOrder = function (value) {
  75337. if (value === 0 || value === 255 || value === -16777216) {
  75338. return 0;
  75339. }
  75340. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  75341. };
  75342. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  75343. var byteArray = new Uint8Array(dataLength);
  75344. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  75345. var index = 0;
  75346. for (var y = 0; y < height; y++) {
  75347. for (var x = 0; x < width; x++) {
  75348. var srcPos = (x + y * width) * 3;
  75349. byteArray[index] = srcData[srcPos + rOffset];
  75350. byteArray[index + 1] = srcData[srcPos + gOffset];
  75351. byteArray[index + 2] = srcData[srcPos + bOffset];
  75352. index += 3;
  75353. }
  75354. }
  75355. return byteArray;
  75356. };
  75357. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  75358. var byteArray = new Uint8Array(dataLength);
  75359. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  75360. var index = 0;
  75361. for (var y = 0; y < height; y++) {
  75362. for (var x = 0; x < width; x++) {
  75363. var srcPos = (x + y * width);
  75364. byteArray[index] = srcData[srcPos];
  75365. index++;
  75366. }
  75367. }
  75368. return byteArray;
  75369. };
  75370. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  75371. if (lodIndex === void 0) { lodIndex = -1; }
  75372. var ext = engine.getCaps().s3tc;
  75373. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  75374. var fourCC, width, height, dataLength = 0, dataOffset;
  75375. var byteArray, mipmapCount, mip;
  75376. var internalFormat = 0;
  75377. var format = 0;
  75378. var blockBytes = 1;
  75379. if (header[off_magic] !== DDS_MAGIC) {
  75380. BABYLON.Tools.Error("Invalid magic number in DDS header");
  75381. return;
  75382. }
  75383. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  75384. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  75385. return;
  75386. }
  75387. if (info.isCompressed && !ext) {
  75388. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  75389. return;
  75390. }
  75391. var bpp = header[off_RGBbpp];
  75392. dataOffset = header[off_size] + 4;
  75393. var computeFormats = false;
  75394. if (info.isFourCC) {
  75395. fourCC = header[off_pfFourCC];
  75396. switch (fourCC) {
  75397. case FOURCC_DXT1:
  75398. blockBytes = 8;
  75399. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  75400. break;
  75401. case FOURCC_DXT3:
  75402. blockBytes = 16;
  75403. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  75404. break;
  75405. case FOURCC_DXT5:
  75406. blockBytes = 16;
  75407. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  75408. break;
  75409. case FOURCC_D3DFMT_R16G16B16A16F:
  75410. computeFormats = true;
  75411. break;
  75412. case FOURCC_D3DFMT_R32G32B32A32F:
  75413. computeFormats = true;
  75414. break;
  75415. case FOURCC_DX10:
  75416. // There is an additionnal header so dataOffset need to be changed
  75417. dataOffset += 5 * 4; // 5 uints
  75418. var supported = false;
  75419. switch (info.dxgiFormat) {
  75420. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  75421. computeFormats = true;
  75422. supported = true;
  75423. break;
  75424. case DXGI_FORMAT_B8G8R8X8_UNORM:
  75425. info.isRGB = true;
  75426. info.isFourCC = false;
  75427. bpp = 32;
  75428. supported = true;
  75429. break;
  75430. }
  75431. if (supported) {
  75432. break;
  75433. }
  75434. default:
  75435. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  75436. return;
  75437. }
  75438. }
  75439. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  75440. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  75441. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  75442. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  75443. if (computeFormats) {
  75444. format = engine._getWebGLTextureType(info.textureType);
  75445. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  75446. }
  75447. mipmapCount = 1;
  75448. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  75449. mipmapCount = Math.max(1, header[off_mipmapCount]);
  75450. }
  75451. for (var face = 0; face < faces; face++) {
  75452. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  75453. width = header[off_width];
  75454. height = header[off_height];
  75455. for (mip = 0; mip < mipmapCount; ++mip) {
  75456. if (lodIndex === -1 || lodIndex === mip) {
  75457. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  75458. var i = (lodIndex === -1) ? mip : 0;
  75459. if (!info.isCompressed && info.isFourCC) {
  75460. dataLength = width * height * 4;
  75461. var floatArray = null;
  75462. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  75463. if (bpp === 128) {
  75464. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  75465. }
  75466. else if (bpp === 64) {
  75467. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  75468. }
  75469. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75470. format = engine._getWebGLTextureType(info.textureType);
  75471. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  75472. }
  75473. else {
  75474. if (bpp === 128) {
  75475. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  75476. }
  75477. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  75478. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  75479. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75480. format = engine._getWebGLTextureType(info.textureType);
  75481. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  75482. }
  75483. else {
  75484. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  75485. }
  75486. }
  75487. if (floatArray) {
  75488. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  75489. }
  75490. }
  75491. else if (info.isRGB) {
  75492. if (bpp === 24) {
  75493. dataLength = width * height * 3;
  75494. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  75495. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  75496. }
  75497. else {
  75498. dataLength = width * height * 4;
  75499. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  75500. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  75501. }
  75502. }
  75503. else if (info.isLuminance) {
  75504. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  75505. var unpaddedRowSize = width;
  75506. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  75507. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  75508. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  75509. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  75510. }
  75511. else {
  75512. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  75513. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  75514. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  75515. }
  75516. }
  75517. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  75518. width *= 0.5;
  75519. height *= 0.5;
  75520. width = Math.max(1.0, width);
  75521. height = Math.max(1.0, height);
  75522. }
  75523. if (currentFace !== undefined) {
  75524. // Loading a single face
  75525. break;
  75526. }
  75527. }
  75528. };
  75529. DDSTools.StoreLODInAlphaChannel = false;
  75530. return DDSTools;
  75531. }());
  75532. BABYLON.DDSTools = DDSTools;
  75533. })(BABYLON || (BABYLON = {}));
  75534. //# sourceMappingURL=babylon.dds.js.map
  75535. var BABYLON;
  75536. (function (BABYLON) {
  75537. /**
  75538. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  75539. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  75540. */
  75541. var KhronosTextureContainer = /** @class */ (function () {
  75542. /**
  75543. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  75544. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  75545. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  75546. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  75547. */
  75548. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  75549. this.arrayBuffer = arrayBuffer;
  75550. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  75551. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  75552. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  75553. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  75554. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  75555. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  75556. BABYLON.Tools.Error("texture missing KTX identifier");
  75557. return;
  75558. }
  75559. // load the reset of the header in native 32 bit int
  75560. var header = new Int32Array(this.arrayBuffer, 12, 13);
  75561. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  75562. var oppositeEndianess = header[0] === 0x01020304;
  75563. // read all the header elements in order they exist in the file, without modification (sans endainness)
  75564. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  75565. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  75566. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  75567. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  75568. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  75569. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  75570. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  75571. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  75572. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  75573. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  75574. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  75575. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  75576. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  75577. if (this.glType !== 0) {
  75578. BABYLON.Tools.Error("only compressed formats currently supported");
  75579. return;
  75580. }
  75581. else {
  75582. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  75583. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  75584. }
  75585. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  75586. BABYLON.Tools.Error("only 2D textures currently supported");
  75587. return;
  75588. }
  75589. if (this.numberOfArrayElements !== 0) {
  75590. BABYLON.Tools.Error("texture arrays not currently supported");
  75591. return;
  75592. }
  75593. if (this.numberOfFaces !== facesExpected) {
  75594. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  75595. return;
  75596. }
  75597. // we now have a completely validated file, so could use existence of loadType as success
  75598. // would need to make this more elaborate & adjust checks above to support more than one load type
  75599. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  75600. }
  75601. // not as fast hardware based, but will probably never need to use
  75602. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  75603. return ((val & 0xFF) << 24)
  75604. | ((val & 0xFF00) << 8)
  75605. | ((val >> 8) & 0xFF00)
  75606. | ((val >> 24) & 0xFF);
  75607. };
  75608. /**
  75609. * It is assumed that the texture has already been created & is currently bound
  75610. */
  75611. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  75612. switch (this.loadType) {
  75613. case KhronosTextureContainer.COMPRESSED_2D:
  75614. this._upload2DCompressedLevels(gl, loadMipmaps);
  75615. break;
  75616. case KhronosTextureContainer.TEX_2D:
  75617. case KhronosTextureContainer.COMPRESSED_3D:
  75618. case KhronosTextureContainer.TEX_3D:
  75619. }
  75620. };
  75621. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  75622. // initialize width & height for level 1
  75623. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  75624. var width = this.pixelWidth;
  75625. var height = this.pixelHeight;
  75626. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  75627. for (var level = 0; level < mipmapCount; level++) {
  75628. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  75629. for (var face = 0; face < this.numberOfFaces; face++) {
  75630. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  75631. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  75632. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  75633. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  75634. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  75635. }
  75636. width = Math.max(1.0, width * 0.5);
  75637. height = Math.max(1.0, height * 0.5);
  75638. }
  75639. };
  75640. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  75641. // load types
  75642. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  75643. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  75644. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  75645. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  75646. return KhronosTextureContainer;
  75647. }());
  75648. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  75649. })(BABYLON || (BABYLON = {}));
  75650. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  75651. var BABYLON;
  75652. (function (BABYLON) {
  75653. var Debug = /** @class */ (function () {
  75654. function Debug() {
  75655. }
  75656. Debug.AxesViewer = /** @class */ (function () {
  75657. function AxesViewer(scene, scaleLines) {
  75658. if (scaleLines === void 0) { scaleLines = 1; }
  75659. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  75660. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  75661. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  75662. this.scaleLines = 1;
  75663. this.scaleLines = scaleLines;
  75664. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  75665. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  75666. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  75667. this._xmesh.renderingGroupId = 2;
  75668. this._ymesh.renderingGroupId = 2;
  75669. this._zmesh.renderingGroupId = 2;
  75670. this._xmesh.material.checkReadyOnlyOnce = true;
  75671. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  75672. this._ymesh.material.checkReadyOnlyOnce = true;
  75673. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  75674. this._zmesh.material.checkReadyOnlyOnce = true;
  75675. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  75676. this.scene = scene;
  75677. }
  75678. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  75679. var scaleLines = this.scaleLines;
  75680. if (this._xmesh) {
  75681. this._xmesh.position.copyFrom(position);
  75682. }
  75683. if (this._ymesh) {
  75684. this._ymesh.position.copyFrom(position);
  75685. }
  75686. if (this._zmesh) {
  75687. this._zmesh.position.copyFrom(position);
  75688. }
  75689. var point2 = this._xline[1];
  75690. point2.x = xaxis.x * scaleLines;
  75691. point2.y = xaxis.y * scaleLines;
  75692. point2.z = xaxis.z * scaleLines;
  75693. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  75694. point2 = this._yline[1];
  75695. point2.x = yaxis.x * scaleLines;
  75696. point2.y = yaxis.y * scaleLines;
  75697. point2.z = yaxis.z * scaleLines;
  75698. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  75699. point2 = this._zline[1];
  75700. point2.x = zaxis.x * scaleLines;
  75701. point2.y = zaxis.y * scaleLines;
  75702. point2.z = zaxis.z * scaleLines;
  75703. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  75704. };
  75705. AxesViewer.prototype.dispose = function () {
  75706. if (this._xmesh) {
  75707. this._xmesh.dispose();
  75708. }
  75709. if (this._ymesh) {
  75710. this._ymesh.dispose();
  75711. }
  75712. if (this._zmesh) {
  75713. this._zmesh.dispose();
  75714. }
  75715. this._xmesh = null;
  75716. this._ymesh = null;
  75717. this._zmesh = null;
  75718. this.scene = null;
  75719. };
  75720. return AxesViewer;
  75721. }());
  75722. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  75723. __extends(BoneAxesViewer, _super);
  75724. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  75725. if (scaleLines === void 0) { scaleLines = 1; }
  75726. var _this = _super.call(this, scene, scaleLines) || this;
  75727. _this.pos = BABYLON.Vector3.Zero();
  75728. _this.xaxis = BABYLON.Vector3.Zero();
  75729. _this.yaxis = BABYLON.Vector3.Zero();
  75730. _this.zaxis = BABYLON.Vector3.Zero();
  75731. _this.mesh = mesh;
  75732. _this.bone = bone;
  75733. return _this;
  75734. }
  75735. BoneAxesViewer.prototype.update = function () {
  75736. if (!this.mesh || !this.bone) {
  75737. return;
  75738. }
  75739. var bone = this.bone;
  75740. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  75741. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  75742. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  75743. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  75744. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  75745. };
  75746. BoneAxesViewer.prototype.dispose = function () {
  75747. if (this.mesh) {
  75748. this.mesh = null;
  75749. this.bone = null;
  75750. _super.prototype.dispose.call(this);
  75751. }
  75752. };
  75753. return BoneAxesViewer;
  75754. }(Debug.AxesViewer));
  75755. Debug.PhysicsViewer = /** @class */ (function () {
  75756. function PhysicsViewer(scene) {
  75757. this._impostors = [];
  75758. this._meshes = [];
  75759. this._numMeshes = 0;
  75760. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  75761. var physicEngine = this._scene.getPhysicsEngine();
  75762. if (physicEngine) {
  75763. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  75764. }
  75765. }
  75766. PhysicsViewer.prototype._updateDebugMeshes = function () {
  75767. var plugin = this._physicsEnginePlugin;
  75768. for (var i = 0; i < this._numMeshes; i++) {
  75769. var impostor = this._impostors[i];
  75770. if (!impostor) {
  75771. continue;
  75772. }
  75773. if (impostor.isDisposed) {
  75774. this.hideImpostor(this._impostors[i--]);
  75775. }
  75776. else {
  75777. var mesh = this._meshes[i];
  75778. if (mesh && plugin) {
  75779. plugin.syncMeshWithImpostor(mesh, impostor);
  75780. }
  75781. }
  75782. }
  75783. };
  75784. PhysicsViewer.prototype.showImpostor = function (impostor) {
  75785. if (!this._scene) {
  75786. return;
  75787. }
  75788. for (var i = 0; i < this._numMeshes; i++) {
  75789. if (this._impostors[i] == impostor) {
  75790. return;
  75791. }
  75792. }
  75793. var debugMesh = this._getDebugMesh(impostor, this._scene);
  75794. if (debugMesh) {
  75795. this._impostors[this._numMeshes] = impostor;
  75796. this._meshes[this._numMeshes] = debugMesh;
  75797. if (this._numMeshes === 0) {
  75798. this._renderFunction = this._updateDebugMeshes.bind(this);
  75799. this._scene.registerBeforeRender(this._renderFunction);
  75800. }
  75801. this._numMeshes++;
  75802. }
  75803. };
  75804. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  75805. if (!impostor || !this._scene) {
  75806. return;
  75807. }
  75808. var removed = false;
  75809. for (var i = 0; i < this._numMeshes; i++) {
  75810. if (this._impostors[i] == impostor) {
  75811. var mesh = this._meshes[i];
  75812. if (!mesh) {
  75813. continue;
  75814. }
  75815. this._scene.removeMesh(mesh);
  75816. mesh.dispose();
  75817. this._numMeshes--;
  75818. if (this._numMeshes > 0) {
  75819. this._meshes[i] = this._meshes[this._numMeshes];
  75820. this._impostors[i] = this._impostors[this._numMeshes];
  75821. this._meshes[this._numMeshes] = null;
  75822. this._impostors[this._numMeshes] = null;
  75823. }
  75824. else {
  75825. this._meshes[0] = null;
  75826. this._impostors[0] = null;
  75827. }
  75828. removed = true;
  75829. break;
  75830. }
  75831. }
  75832. if (removed && this._numMeshes === 0) {
  75833. this._scene.unregisterBeforeRender(this._renderFunction);
  75834. }
  75835. };
  75836. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  75837. if (!this._debugMaterial) {
  75838. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  75839. this._debugMaterial.wireframe = true;
  75840. }
  75841. return this._debugMaterial;
  75842. };
  75843. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  75844. if (!this._debugBoxMesh) {
  75845. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  75846. this._debugBoxMesh.renderingGroupId = 1;
  75847. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  75848. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  75849. scene.removeMesh(this._debugBoxMesh);
  75850. }
  75851. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  75852. };
  75853. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  75854. if (!this._debugSphereMesh) {
  75855. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  75856. this._debugSphereMesh.renderingGroupId = 1;
  75857. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  75858. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  75859. scene.removeMesh(this._debugSphereMesh);
  75860. }
  75861. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  75862. };
  75863. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  75864. var mesh = null;
  75865. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  75866. mesh = this._getDebugBoxMesh(scene);
  75867. impostor.getBoxSizeToRef(mesh.scaling);
  75868. }
  75869. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  75870. mesh = this._getDebugSphereMesh(scene);
  75871. var radius = impostor.getRadius();
  75872. mesh.scaling.x = radius * 2;
  75873. mesh.scaling.y = radius * 2;
  75874. mesh.scaling.z = radius * 2;
  75875. }
  75876. return mesh;
  75877. };
  75878. PhysicsViewer.prototype.dispose = function () {
  75879. for (var i = 0; i < this._numMeshes; i++) {
  75880. this.hideImpostor(this._impostors[i]);
  75881. }
  75882. if (this._debugBoxMesh) {
  75883. this._debugBoxMesh.dispose();
  75884. }
  75885. if (this._debugSphereMesh) {
  75886. this._debugSphereMesh.dispose();
  75887. }
  75888. if (this._debugMaterial) {
  75889. this._debugMaterial.dispose();
  75890. }
  75891. this._impostors.length = 0;
  75892. this._scene = null;
  75893. this._physicsEnginePlugin = null;
  75894. };
  75895. return PhysicsViewer;
  75896. }());
  75897. Debug.SkeletonViewer = /** @class */ (function () {
  75898. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  75899. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  75900. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  75901. this.skeleton = skeleton;
  75902. this.mesh = mesh;
  75903. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  75904. this.renderingGroupId = renderingGroupId;
  75905. this.color = BABYLON.Color3.White();
  75906. this._debugLines = new Array();
  75907. this._isEnabled = false;
  75908. this._scene = scene;
  75909. this.update();
  75910. this._renderFunction = this.update.bind(this);
  75911. }
  75912. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  75913. get: function () {
  75914. return this._isEnabled;
  75915. },
  75916. set: function (value) {
  75917. if (this._isEnabled === value) {
  75918. return;
  75919. }
  75920. this._isEnabled = value;
  75921. if (value) {
  75922. this._scene.registerBeforeRender(this._renderFunction);
  75923. }
  75924. else {
  75925. this._scene.unregisterBeforeRender(this._renderFunction);
  75926. }
  75927. },
  75928. enumerable: true,
  75929. configurable: true
  75930. });
  75931. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  75932. if (x === void 0) { x = 0; }
  75933. if (y === void 0) { y = 0; }
  75934. if (z === void 0) { z = 0; }
  75935. var tmat = BABYLON.Tmp.Matrix[0];
  75936. var parentBone = bone.getParent();
  75937. tmat.copyFrom(bone.getLocalMatrix());
  75938. if (x !== 0 || y !== 0 || z !== 0) {
  75939. var tmat2 = BABYLON.Tmp.Matrix[1];
  75940. BABYLON.Matrix.IdentityToRef(tmat2);
  75941. tmat2.m[12] = x;
  75942. tmat2.m[13] = y;
  75943. tmat2.m[14] = z;
  75944. tmat2.multiplyToRef(tmat, tmat);
  75945. }
  75946. if (parentBone) {
  75947. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  75948. }
  75949. tmat.multiplyToRef(meshMat, tmat);
  75950. position.x = tmat.m[12];
  75951. position.y = tmat.m[13];
  75952. position.z = tmat.m[14];
  75953. };
  75954. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  75955. var len = bones.length;
  75956. var meshPos = this.mesh.position;
  75957. for (var i = 0; i < len; i++) {
  75958. var bone = bones[i];
  75959. var points = this._debugLines[i];
  75960. if (!points) {
  75961. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  75962. this._debugLines[i] = points;
  75963. }
  75964. this._getBonePosition(points[0], bone, meshMat);
  75965. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  75966. points[0].subtractInPlace(meshPos);
  75967. points[1].subtractInPlace(meshPos);
  75968. }
  75969. };
  75970. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  75971. var len = bones.length;
  75972. var boneNum = 0;
  75973. var meshPos = this.mesh.position;
  75974. for (var i = len - 1; i >= 0; i--) {
  75975. var childBone = bones[i];
  75976. var parentBone = childBone.getParent();
  75977. if (!parentBone) {
  75978. continue;
  75979. }
  75980. var points = this._debugLines[boneNum];
  75981. if (!points) {
  75982. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  75983. this._debugLines[boneNum] = points;
  75984. }
  75985. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  75986. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  75987. points[0].subtractInPlace(meshPos);
  75988. points[1].subtractInPlace(meshPos);
  75989. boneNum++;
  75990. }
  75991. };
  75992. SkeletonViewer.prototype.update = function () {
  75993. if (this.autoUpdateBonesMatrices) {
  75994. this.skeleton.computeAbsoluteTransforms();
  75995. }
  75996. if (this.skeleton.bones[0].length === undefined) {
  75997. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  75998. }
  75999. else {
  76000. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  76001. }
  76002. if (!this._debugMesh) {
  76003. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  76004. this._debugMesh.renderingGroupId = this.renderingGroupId;
  76005. }
  76006. else {
  76007. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  76008. }
  76009. this._debugMesh.position.copyFrom(this.mesh.position);
  76010. this._debugMesh.color = this.color;
  76011. };
  76012. SkeletonViewer.prototype.dispose = function () {
  76013. if (this._debugMesh) {
  76014. this.isEnabled = false;
  76015. this._debugMesh.dispose();
  76016. this._debugMesh = null;
  76017. }
  76018. };
  76019. return SkeletonViewer;
  76020. }());
  76021. return Debug;
  76022. }());
  76023. BABYLON.Debug = Debug;
  76024. })(BABYLON || (BABYLON = {}));
  76025. //# sourceMappingURL=babylon.debugModules.js.map
  76026. var BABYLON;
  76027. (function (BABYLON) {
  76028. var RayHelper = /** @class */ (function () {
  76029. function RayHelper(ray) {
  76030. this.ray = ray;
  76031. }
  76032. RayHelper.CreateAndShow = function (ray, scene, color) {
  76033. var helper = new RayHelper(ray);
  76034. helper.show(scene, color);
  76035. return helper;
  76036. };
  76037. RayHelper.prototype.show = function (scene, color) {
  76038. if (!this._renderFunction && this.ray) {
  76039. var ray = this.ray;
  76040. this._renderFunction = this._render.bind(this);
  76041. this._scene = scene;
  76042. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  76043. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  76044. if (this._renderFunction) {
  76045. this._scene.registerBeforeRender(this._renderFunction);
  76046. }
  76047. }
  76048. if (color && this._renderLine) {
  76049. this._renderLine.color.copyFrom(color);
  76050. }
  76051. };
  76052. RayHelper.prototype.hide = function () {
  76053. if (this._renderFunction && this._scene) {
  76054. this._scene.unregisterBeforeRender(this._renderFunction);
  76055. this._scene = null;
  76056. this._renderFunction = null;
  76057. if (this._renderLine) {
  76058. this._renderLine.dispose();
  76059. this._renderLine = null;
  76060. }
  76061. this._renderPoints = [];
  76062. }
  76063. };
  76064. RayHelper.prototype._render = function () {
  76065. var ray = this.ray;
  76066. if (!ray) {
  76067. return;
  76068. }
  76069. var point = this._renderPoints[1];
  76070. var len = Math.min(ray.length, 1000000);
  76071. point.copyFrom(ray.direction);
  76072. point.scaleInPlace(len);
  76073. point.addInPlace(ray.origin);
  76074. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  76075. };
  76076. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  76077. this._attachedToMesh = mesh;
  76078. var ray = this.ray;
  76079. if (!ray) {
  76080. return;
  76081. }
  76082. if (!ray.direction) {
  76083. ray.direction = BABYLON.Vector3.Zero();
  76084. }
  76085. if (!ray.origin) {
  76086. ray.origin = BABYLON.Vector3.Zero();
  76087. }
  76088. if (length) {
  76089. ray.length = length;
  76090. }
  76091. if (!meshSpaceOrigin) {
  76092. meshSpaceOrigin = BABYLON.Vector3.Zero();
  76093. }
  76094. if (!meshSpaceDirection) {
  76095. // -1 so that this will work with Mesh.lookAt
  76096. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  76097. }
  76098. if (!this._meshSpaceDirection) {
  76099. this._meshSpaceDirection = meshSpaceDirection.clone();
  76100. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  76101. }
  76102. else {
  76103. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  76104. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  76105. }
  76106. if (!this._updateToMeshFunction) {
  76107. this._updateToMeshFunction = this._updateToMesh.bind(this);
  76108. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  76109. }
  76110. this._updateToMesh();
  76111. };
  76112. RayHelper.prototype.detachFromMesh = function () {
  76113. if (this._attachedToMesh) {
  76114. if (this._updateToMeshFunction) {
  76115. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  76116. }
  76117. this._attachedToMesh = null;
  76118. this._updateToMeshFunction = null;
  76119. }
  76120. };
  76121. RayHelper.prototype._updateToMesh = function () {
  76122. var ray = this.ray;
  76123. if (!this._attachedToMesh || !ray) {
  76124. return;
  76125. }
  76126. if (this._attachedToMesh._isDisposed) {
  76127. this.detachFromMesh();
  76128. return;
  76129. }
  76130. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  76131. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  76132. };
  76133. RayHelper.prototype.dispose = function () {
  76134. this.hide();
  76135. this.detachFromMesh();
  76136. this.ray = null;
  76137. };
  76138. return RayHelper;
  76139. }());
  76140. BABYLON.RayHelper = RayHelper;
  76141. })(BABYLON || (BABYLON = {}));
  76142. //# sourceMappingURL=babylon.rayHelper.js.map
  76143. var BABYLON;
  76144. (function (BABYLON) {
  76145. // load the inspector using require, if not present in the global namespace.
  76146. var DebugLayer = /** @class */ (function () {
  76147. function DebugLayer(scene) {
  76148. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  76149. this._scene = scene;
  76150. // load inspector using require, if it doesn't exist on the global namespace.
  76151. }
  76152. /** Creates the inspector window. */
  76153. DebugLayer.prototype._createInspector = function (config) {
  76154. if (config === void 0) { config = {}; }
  76155. var popup = config.popup || false;
  76156. var initialTab = config.initialTab || 0;
  76157. var parentElement = config.parentElement || null;
  76158. if (!this._inspector) {
  76159. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  76160. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  76161. } // else nothing to do,; instance is already existing
  76162. };
  76163. DebugLayer.prototype.isVisible = function () {
  76164. if (!this._inspector) {
  76165. return false;
  76166. }
  76167. return true;
  76168. };
  76169. DebugLayer.prototype.hide = function () {
  76170. if (this._inspector) {
  76171. try {
  76172. this._inspector.dispose();
  76173. }
  76174. catch (e) {
  76175. // If the inspector has been removed directly from the inspector tool
  76176. }
  76177. this._inspector = null;
  76178. }
  76179. };
  76180. DebugLayer.prototype.show = function (config) {
  76181. if (config === void 0) { config = {}; }
  76182. if (typeof this.BJSINSPECTOR == 'undefined') {
  76183. // Load inspector and add it to the DOM
  76184. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  76185. }
  76186. else {
  76187. // Otherwise creates the inspector
  76188. this._createInspector(config);
  76189. }
  76190. };
  76191. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  76192. return DebugLayer;
  76193. }());
  76194. BABYLON.DebugLayer = DebugLayer;
  76195. })(BABYLON || (BABYLON = {}));
  76196. //# sourceMappingURL=babylon.debugLayer.js.map
  76197. var BABYLON;
  76198. (function (BABYLON) {
  76199. var BoundingBoxRenderer = /** @class */ (function () {
  76200. function BoundingBoxRenderer(scene) {
  76201. this.frontColor = new BABYLON.Color3(1, 1, 1);
  76202. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  76203. this.showBackLines = true;
  76204. this.renderList = new BABYLON.SmartArray(32);
  76205. this._vertexBuffers = {};
  76206. this._scene = scene;
  76207. }
  76208. BoundingBoxRenderer.prototype._prepareRessources = function () {
  76209. if (this._colorShader) {
  76210. return;
  76211. }
  76212. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  76213. attributes: [BABYLON.VertexBuffer.PositionKind],
  76214. uniforms: ["world", "viewProjection", "color"]
  76215. });
  76216. var engine = this._scene.getEngine();
  76217. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  76218. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  76219. this._createIndexBuffer();
  76220. };
  76221. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  76222. var engine = this._scene.getEngine();
  76223. 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]);
  76224. };
  76225. BoundingBoxRenderer.prototype._rebuild = function () {
  76226. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76227. if (vb) {
  76228. vb._rebuild();
  76229. }
  76230. this._createIndexBuffer();
  76231. };
  76232. BoundingBoxRenderer.prototype.reset = function () {
  76233. this.renderList.reset();
  76234. };
  76235. BoundingBoxRenderer.prototype.render = function () {
  76236. if (this.renderList.length === 0) {
  76237. return;
  76238. }
  76239. this._prepareRessources();
  76240. if (!this._colorShader.isReady()) {
  76241. return;
  76242. }
  76243. var engine = this._scene.getEngine();
  76244. engine.setDepthWrite(false);
  76245. this._colorShader._preBind();
  76246. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  76247. var boundingBox = this.renderList.data[boundingBoxIndex];
  76248. var min = boundingBox.minimum;
  76249. var max = boundingBox.maximum;
  76250. var diff = max.subtract(min);
  76251. var median = min.add(diff.scale(0.5));
  76252. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  76253. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  76254. .multiply(boundingBox.getWorldMatrix());
  76255. // VBOs
  76256. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  76257. if (this.showBackLines) {
  76258. // Back
  76259. engine.setDepthFunctionToGreaterOrEqual();
  76260. this._scene.resetCachedMaterial();
  76261. this._colorShader.setColor4("color", this.backColor.toColor4());
  76262. this._colorShader.bind(worldMatrix);
  76263. // Draw order
  76264. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  76265. }
  76266. // Front
  76267. engine.setDepthFunctionToLess();
  76268. this._scene.resetCachedMaterial();
  76269. this._colorShader.setColor4("color", this.frontColor.toColor4());
  76270. this._colorShader.bind(worldMatrix);
  76271. // Draw order
  76272. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  76273. }
  76274. this._colorShader.unbind();
  76275. engine.setDepthFunctionToLessOrEqual();
  76276. engine.setDepthWrite(true);
  76277. };
  76278. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  76279. this._prepareRessources();
  76280. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  76281. return;
  76282. }
  76283. var engine = this._scene.getEngine();
  76284. engine.setDepthWrite(false);
  76285. engine.setColorWrite(false);
  76286. this._colorShader._preBind();
  76287. var boundingBox = mesh._boundingInfo.boundingBox;
  76288. var min = boundingBox.minimum;
  76289. var max = boundingBox.maximum;
  76290. var diff = max.subtract(min);
  76291. var median = min.add(diff.scale(0.5));
  76292. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  76293. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  76294. .multiply(boundingBox.getWorldMatrix());
  76295. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  76296. engine.setDepthFunctionToLess();
  76297. this._scene.resetCachedMaterial();
  76298. this._colorShader.bind(worldMatrix);
  76299. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  76300. this._colorShader.unbind();
  76301. engine.setDepthFunctionToLessOrEqual();
  76302. engine.setDepthWrite(true);
  76303. engine.setColorWrite(true);
  76304. };
  76305. BoundingBoxRenderer.prototype.dispose = function () {
  76306. if (!this._colorShader) {
  76307. return;
  76308. }
  76309. this.renderList.dispose();
  76310. this._colorShader.dispose();
  76311. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76312. if (buffer) {
  76313. buffer.dispose();
  76314. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76315. }
  76316. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  76317. };
  76318. return BoundingBoxRenderer;
  76319. }());
  76320. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  76321. })(BABYLON || (BABYLON = {}));
  76322. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  76323. var BABYLON;
  76324. (function (BABYLON) {
  76325. var MorphTarget = /** @class */ (function () {
  76326. function MorphTarget(name, influence) {
  76327. if (influence === void 0) { influence = 0; }
  76328. this.name = name;
  76329. this.animations = new Array();
  76330. this._positions = null;
  76331. this._normals = null;
  76332. this._tangents = null;
  76333. this.onInfluenceChanged = new BABYLON.Observable();
  76334. this.influence = influence;
  76335. }
  76336. Object.defineProperty(MorphTarget.prototype, "influence", {
  76337. get: function () {
  76338. return this._influence;
  76339. },
  76340. set: function (influence) {
  76341. if (this._influence === influence) {
  76342. return;
  76343. }
  76344. var previous = this._influence;
  76345. this._influence = influence;
  76346. if (this.onInfluenceChanged.hasObservers) {
  76347. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  76348. }
  76349. },
  76350. enumerable: true,
  76351. configurable: true
  76352. });
  76353. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  76354. get: function () {
  76355. return !!this._positions;
  76356. },
  76357. enumerable: true,
  76358. configurable: true
  76359. });
  76360. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  76361. get: function () {
  76362. return !!this._normals;
  76363. },
  76364. enumerable: true,
  76365. configurable: true
  76366. });
  76367. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  76368. get: function () {
  76369. return !!this._tangents;
  76370. },
  76371. enumerable: true,
  76372. configurable: true
  76373. });
  76374. MorphTarget.prototype.setPositions = function (data) {
  76375. this._positions = data;
  76376. };
  76377. MorphTarget.prototype.getPositions = function () {
  76378. return this._positions;
  76379. };
  76380. MorphTarget.prototype.setNormals = function (data) {
  76381. this._normals = data;
  76382. };
  76383. MorphTarget.prototype.getNormals = function () {
  76384. return this._normals;
  76385. };
  76386. MorphTarget.prototype.setTangents = function (data) {
  76387. this._tangents = data;
  76388. };
  76389. MorphTarget.prototype.getTangents = function () {
  76390. return this._tangents;
  76391. };
  76392. /**
  76393. * Serializes the current target into a Serialization object.
  76394. * Returns the serialized object.
  76395. */
  76396. MorphTarget.prototype.serialize = function () {
  76397. var serializationObject = {};
  76398. serializationObject.name = this.name;
  76399. serializationObject.influence = this.influence;
  76400. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  76401. if (this.hasNormals) {
  76402. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  76403. }
  76404. if (this.hasTangents) {
  76405. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  76406. }
  76407. // Animations
  76408. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  76409. return serializationObject;
  76410. };
  76411. // Statics
  76412. MorphTarget.Parse = function (serializationObject) {
  76413. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  76414. result.setPositions(serializationObject.positions);
  76415. if (serializationObject.normals) {
  76416. result.setNormals(serializationObject.normals);
  76417. }
  76418. if (serializationObject.tangents) {
  76419. result.setTangents(serializationObject.tangents);
  76420. }
  76421. // Animations
  76422. if (serializationObject.animations) {
  76423. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  76424. var parsedAnimation = serializationObject.animations[animationIndex];
  76425. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  76426. }
  76427. }
  76428. return result;
  76429. };
  76430. MorphTarget.FromMesh = function (mesh, name, influence) {
  76431. if (!name) {
  76432. name = mesh.name;
  76433. }
  76434. var result = new MorphTarget(name, influence);
  76435. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  76436. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  76437. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  76438. }
  76439. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  76440. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  76441. }
  76442. return result;
  76443. };
  76444. return MorphTarget;
  76445. }());
  76446. BABYLON.MorphTarget = MorphTarget;
  76447. })(BABYLON || (BABYLON = {}));
  76448. //# sourceMappingURL=babylon.morphTarget.js.map
  76449. var BABYLON;
  76450. (function (BABYLON) {
  76451. var MorphTargetManager = /** @class */ (function () {
  76452. function MorphTargetManager(scene) {
  76453. if (scene === void 0) { scene = null; }
  76454. this._targets = new Array();
  76455. this._targetObservable = new Array();
  76456. this._activeTargets = new BABYLON.SmartArray(16);
  76457. this._supportsNormals = false;
  76458. this._supportsTangents = false;
  76459. this._vertexCount = 0;
  76460. this._uniqueId = 0;
  76461. this._tempInfluences = new Array();
  76462. if (!scene) {
  76463. scene = BABYLON.Engine.LastCreatedScene;
  76464. }
  76465. this._scene = scene;
  76466. if (this._scene) {
  76467. this._scene.morphTargetManagers.push(this);
  76468. this._uniqueId = this._scene.getUniqueId();
  76469. }
  76470. }
  76471. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  76472. get: function () {
  76473. return this._uniqueId;
  76474. },
  76475. enumerable: true,
  76476. configurable: true
  76477. });
  76478. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  76479. get: function () {
  76480. return this._vertexCount;
  76481. },
  76482. enumerable: true,
  76483. configurable: true
  76484. });
  76485. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  76486. get: function () {
  76487. return this._supportsNormals;
  76488. },
  76489. enumerable: true,
  76490. configurable: true
  76491. });
  76492. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  76493. get: function () {
  76494. return this._supportsTangents;
  76495. },
  76496. enumerable: true,
  76497. configurable: true
  76498. });
  76499. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  76500. get: function () {
  76501. return this._targets.length;
  76502. },
  76503. enumerable: true,
  76504. configurable: true
  76505. });
  76506. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  76507. get: function () {
  76508. return this._activeTargets.length;
  76509. },
  76510. enumerable: true,
  76511. configurable: true
  76512. });
  76513. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  76514. get: function () {
  76515. return this._influences;
  76516. },
  76517. enumerable: true,
  76518. configurable: true
  76519. });
  76520. MorphTargetManager.prototype.getActiveTarget = function (index) {
  76521. return this._activeTargets.data[index];
  76522. };
  76523. MorphTargetManager.prototype.getTarget = function (index) {
  76524. return this._targets[index];
  76525. };
  76526. MorphTargetManager.prototype.addTarget = function (target) {
  76527. var _this = this;
  76528. this._targets.push(target);
  76529. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  76530. _this._syncActiveTargets(needUpdate);
  76531. }));
  76532. this._syncActiveTargets(true);
  76533. };
  76534. MorphTargetManager.prototype.removeTarget = function (target) {
  76535. var index = this._targets.indexOf(target);
  76536. if (index >= 0) {
  76537. this._targets.splice(index, 1);
  76538. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  76539. this._syncActiveTargets(true);
  76540. }
  76541. };
  76542. /**
  76543. * Serializes the current manager into a Serialization object.
  76544. * Returns the serialized object.
  76545. */
  76546. MorphTargetManager.prototype.serialize = function () {
  76547. var serializationObject = {};
  76548. serializationObject.id = this.uniqueId;
  76549. serializationObject.targets = [];
  76550. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  76551. var target = _a[_i];
  76552. serializationObject.targets.push(target.serialize());
  76553. }
  76554. return serializationObject;
  76555. };
  76556. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  76557. var influenceCount = 0;
  76558. this._activeTargets.reset();
  76559. this._supportsNormals = true;
  76560. this._supportsTangents = true;
  76561. this._vertexCount = 0;
  76562. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  76563. var target = _a[_i];
  76564. this._activeTargets.push(target);
  76565. this._tempInfluences[influenceCount++] = target.influence;
  76566. var positions = target.getPositions();
  76567. if (positions) {
  76568. this._supportsNormals = this._supportsNormals && target.hasNormals;
  76569. this._supportsTangents = this._supportsTangents && target.hasTangents;
  76570. var vertexCount = positions.length / 3;
  76571. if (this._vertexCount === 0) {
  76572. this._vertexCount = vertexCount;
  76573. }
  76574. else if (this._vertexCount !== vertexCount) {
  76575. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  76576. return;
  76577. }
  76578. }
  76579. }
  76580. if (!this._influences || this._influences.length !== influenceCount) {
  76581. this._influences = new Float32Array(influenceCount);
  76582. }
  76583. for (var index = 0; index < influenceCount; index++) {
  76584. this._influences[index] = this._tempInfluences[index];
  76585. }
  76586. if (needUpdate && this._scene) {
  76587. // Flag meshes as dirty to resync with the active targets
  76588. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  76589. var mesh = _c[_b];
  76590. if (mesh.morphTargetManager === this) {
  76591. mesh._syncGeometryWithMorphTargetManager();
  76592. }
  76593. }
  76594. }
  76595. };
  76596. // Statics
  76597. MorphTargetManager.Parse = function (serializationObject, scene) {
  76598. var result = new MorphTargetManager(scene);
  76599. result._uniqueId = serializationObject.id;
  76600. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  76601. var targetData = _a[_i];
  76602. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  76603. }
  76604. return result;
  76605. };
  76606. return MorphTargetManager;
  76607. }());
  76608. BABYLON.MorphTargetManager = MorphTargetManager;
  76609. })(BABYLON || (BABYLON = {}));
  76610. //# sourceMappingURL=babylon.morphTargetManager.js.map
  76611. var BABYLON;
  76612. (function (BABYLON) {
  76613. var Octree = /** @class */ (function () {
  76614. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  76615. if (maxDepth === void 0) { maxDepth = 2; }
  76616. this.maxDepth = maxDepth;
  76617. this.dynamicContent = new Array();
  76618. this._maxBlockCapacity = maxBlockCapacity || 64;
  76619. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  76620. this._creationFunc = creationFunc;
  76621. }
  76622. // Methods
  76623. Octree.prototype.update = function (worldMin, worldMax, entries) {
  76624. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  76625. };
  76626. Octree.prototype.addMesh = function (entry) {
  76627. for (var index = 0; index < this.blocks.length; index++) {
  76628. var block = this.blocks[index];
  76629. block.addEntry(entry);
  76630. }
  76631. };
  76632. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  76633. this._selectionContent.reset();
  76634. for (var index = 0; index < this.blocks.length; index++) {
  76635. var block = this.blocks[index];
  76636. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  76637. }
  76638. if (allowDuplicate) {
  76639. this._selectionContent.concat(this.dynamicContent);
  76640. }
  76641. else {
  76642. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  76643. }
  76644. return this._selectionContent;
  76645. };
  76646. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  76647. this._selectionContent.reset();
  76648. for (var index = 0; index < this.blocks.length; index++) {
  76649. var block = this.blocks[index];
  76650. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  76651. }
  76652. if (allowDuplicate) {
  76653. this._selectionContent.concat(this.dynamicContent);
  76654. }
  76655. else {
  76656. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  76657. }
  76658. return this._selectionContent;
  76659. };
  76660. Octree.prototype.intersectsRay = function (ray) {
  76661. this._selectionContent.reset();
  76662. for (var index = 0; index < this.blocks.length; index++) {
  76663. var block = this.blocks[index];
  76664. block.intersectsRay(ray, this._selectionContent);
  76665. }
  76666. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  76667. return this._selectionContent;
  76668. };
  76669. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  76670. target.blocks = new Array();
  76671. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  76672. // Segmenting space
  76673. for (var x = 0; x < 2; x++) {
  76674. for (var y = 0; y < 2; y++) {
  76675. for (var z = 0; z < 2; z++) {
  76676. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  76677. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  76678. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  76679. block.addEntries(entries);
  76680. target.blocks.push(block);
  76681. }
  76682. }
  76683. }
  76684. };
  76685. Octree.CreationFuncForMeshes = function (entry, block) {
  76686. var boundingInfo = entry.getBoundingInfo();
  76687. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  76688. block.entries.push(entry);
  76689. }
  76690. };
  76691. Octree.CreationFuncForSubMeshes = function (entry, block) {
  76692. var boundingInfo = entry.getBoundingInfo();
  76693. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  76694. block.entries.push(entry);
  76695. }
  76696. };
  76697. return Octree;
  76698. }());
  76699. BABYLON.Octree = Octree;
  76700. })(BABYLON || (BABYLON = {}));
  76701. //# sourceMappingURL=babylon.octree.js.map
  76702. var BABYLON;
  76703. (function (BABYLON) {
  76704. var OctreeBlock = /** @class */ (function () {
  76705. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  76706. this.entries = new Array();
  76707. this._boundingVectors = new Array();
  76708. this._capacity = capacity;
  76709. this._depth = depth;
  76710. this._maxDepth = maxDepth;
  76711. this._creationFunc = creationFunc;
  76712. this._minPoint = minPoint;
  76713. this._maxPoint = maxPoint;
  76714. this._boundingVectors.push(minPoint.clone());
  76715. this._boundingVectors.push(maxPoint.clone());
  76716. this._boundingVectors.push(minPoint.clone());
  76717. this._boundingVectors[2].x = maxPoint.x;
  76718. this._boundingVectors.push(minPoint.clone());
  76719. this._boundingVectors[3].y = maxPoint.y;
  76720. this._boundingVectors.push(minPoint.clone());
  76721. this._boundingVectors[4].z = maxPoint.z;
  76722. this._boundingVectors.push(maxPoint.clone());
  76723. this._boundingVectors[5].z = minPoint.z;
  76724. this._boundingVectors.push(maxPoint.clone());
  76725. this._boundingVectors[6].x = minPoint.x;
  76726. this._boundingVectors.push(maxPoint.clone());
  76727. this._boundingVectors[7].y = minPoint.y;
  76728. }
  76729. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  76730. // Property
  76731. get: function () {
  76732. return this._capacity;
  76733. },
  76734. enumerable: true,
  76735. configurable: true
  76736. });
  76737. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  76738. get: function () {
  76739. return this._minPoint;
  76740. },
  76741. enumerable: true,
  76742. configurable: true
  76743. });
  76744. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  76745. get: function () {
  76746. return this._maxPoint;
  76747. },
  76748. enumerable: true,
  76749. configurable: true
  76750. });
  76751. // Methods
  76752. OctreeBlock.prototype.addEntry = function (entry) {
  76753. if (this.blocks) {
  76754. for (var index = 0; index < this.blocks.length; index++) {
  76755. var block = this.blocks[index];
  76756. block.addEntry(entry);
  76757. }
  76758. return;
  76759. }
  76760. this._creationFunc(entry, this);
  76761. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  76762. this.createInnerBlocks();
  76763. }
  76764. };
  76765. OctreeBlock.prototype.addEntries = function (entries) {
  76766. for (var index = 0; index < entries.length; index++) {
  76767. var mesh = entries[index];
  76768. this.addEntry(mesh);
  76769. }
  76770. };
  76771. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  76772. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  76773. if (this.blocks) {
  76774. for (var index = 0; index < this.blocks.length; index++) {
  76775. var block = this.blocks[index];
  76776. block.select(frustumPlanes, selection, allowDuplicate);
  76777. }
  76778. return;
  76779. }
  76780. if (allowDuplicate) {
  76781. selection.concat(this.entries);
  76782. }
  76783. else {
  76784. selection.concatWithNoDuplicate(this.entries);
  76785. }
  76786. }
  76787. };
  76788. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  76789. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  76790. if (this.blocks) {
  76791. for (var index = 0; index < this.blocks.length; index++) {
  76792. var block = this.blocks[index];
  76793. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  76794. }
  76795. return;
  76796. }
  76797. if (allowDuplicate) {
  76798. selection.concat(this.entries);
  76799. }
  76800. else {
  76801. selection.concatWithNoDuplicate(this.entries);
  76802. }
  76803. }
  76804. };
  76805. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  76806. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  76807. if (this.blocks) {
  76808. for (var index = 0; index < this.blocks.length; index++) {
  76809. var block = this.blocks[index];
  76810. block.intersectsRay(ray, selection);
  76811. }
  76812. return;
  76813. }
  76814. selection.concatWithNoDuplicate(this.entries);
  76815. }
  76816. };
  76817. OctreeBlock.prototype.createInnerBlocks = function () {
  76818. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  76819. };
  76820. return OctreeBlock;
  76821. }());
  76822. BABYLON.OctreeBlock = OctreeBlock;
  76823. })(BABYLON || (BABYLON = {}));
  76824. //# sourceMappingURL=babylon.octreeBlock.js.map
  76825. var BABYLON;
  76826. (function (BABYLON) {
  76827. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  76828. __extends(VRDistortionCorrectionPostProcess, _super);
  76829. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  76830. var _this = _super.call(this, name, "vrDistortionCorrection", [
  76831. 'LensCenter',
  76832. 'Scale',
  76833. 'ScaleIn',
  76834. 'HmdWarpParam'
  76835. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  76836. _this._isRightEye = isRightEye;
  76837. _this._distortionFactors = vrMetrics.distortionK;
  76838. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  76839. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  76840. _this.adaptScaleToCurrentViewport = true;
  76841. _this.onSizeChangedObservable.add(function () {
  76842. _this.aspectRatio = _this.width * .5 / _this.height;
  76843. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  76844. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  76845. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  76846. });
  76847. _this.onApplyObservable.add(function (effect) {
  76848. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  76849. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  76850. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  76851. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  76852. });
  76853. return _this;
  76854. }
  76855. return VRDistortionCorrectionPostProcess;
  76856. }(BABYLON.PostProcess));
  76857. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  76858. })(BABYLON || (BABYLON = {}));
  76859. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  76860. var BABYLON;
  76861. (function (BABYLON) {
  76862. var AnaglyphPostProcess = /** @class */ (function (_super) {
  76863. __extends(AnaglyphPostProcess, _super);
  76864. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  76865. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  76866. _this._passedProcess = rigCameras[0]._rigPostProcess;
  76867. _this.onApplyObservable.add(function (effect) {
  76868. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  76869. });
  76870. return _this;
  76871. }
  76872. return AnaglyphPostProcess;
  76873. }(BABYLON.PostProcess));
  76874. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  76875. })(BABYLON || (BABYLON = {}));
  76876. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  76877. var BABYLON;
  76878. (function (BABYLON) {
  76879. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  76880. __extends(StereoscopicInterlacePostProcess, _super);
  76881. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  76882. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  76883. _this._passedProcess = rigCameras[0]._rigPostProcess;
  76884. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  76885. _this.onSizeChangedObservable.add(function () {
  76886. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  76887. });
  76888. _this.onApplyObservable.add(function (effect) {
  76889. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  76890. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  76891. });
  76892. return _this;
  76893. }
  76894. return StereoscopicInterlacePostProcess;
  76895. }(BABYLON.PostProcess));
  76896. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  76897. })(BABYLON || (BABYLON = {}));
  76898. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  76899. var BABYLON;
  76900. (function (BABYLON) {
  76901. /**
  76902. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  76903. * Screen rotation is taken into account.
  76904. */
  76905. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  76906. function FreeCameraDeviceOrientationInput() {
  76907. var _this = this;
  76908. this._screenOrientationAngle = 0;
  76909. this._screenQuaternion = new BABYLON.Quaternion();
  76910. this._alpha = 0;
  76911. this._beta = 0;
  76912. this._gamma = 0;
  76913. this._orientationChanged = function () {
  76914. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  76915. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  76916. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  76917. };
  76918. this._deviceOrientation = function (evt) {
  76919. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  76920. _this._beta = evt.beta !== null ? evt.beta : 0;
  76921. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  76922. };
  76923. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  76924. this._orientationChanged();
  76925. }
  76926. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  76927. get: function () {
  76928. return this._camera;
  76929. },
  76930. set: function (camera) {
  76931. this._camera = camera;
  76932. if (this._camera != null && !this._camera.rotationQuaternion) {
  76933. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  76934. }
  76935. },
  76936. enumerable: true,
  76937. configurable: true
  76938. });
  76939. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  76940. window.addEventListener("orientationchange", this._orientationChanged);
  76941. window.addEventListener("deviceorientation", this._deviceOrientation);
  76942. //In certain cases, the attach control is called AFTER orientation was changed,
  76943. //So this is needed.
  76944. this._orientationChanged();
  76945. };
  76946. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  76947. window.removeEventListener("orientationchange", this._orientationChanged);
  76948. window.removeEventListener("deviceorientation", this._deviceOrientation);
  76949. };
  76950. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  76951. //if no device orientation provided, don't update the rotation.
  76952. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  76953. if (!this._alpha)
  76954. return;
  76955. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  76956. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  76957. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  76958. //Mirror on XY Plane
  76959. this._camera.rotationQuaternion.z *= -1;
  76960. this._camera.rotationQuaternion.w *= -1;
  76961. };
  76962. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  76963. return "FreeCameraDeviceOrientationInput";
  76964. };
  76965. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  76966. return "deviceOrientation";
  76967. };
  76968. return FreeCameraDeviceOrientationInput;
  76969. }());
  76970. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  76971. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  76972. })(BABYLON || (BABYLON = {}));
  76973. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  76974. var BABYLON;
  76975. (function (BABYLON) {
  76976. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  76977. function ArcRotateCameraVRDeviceOrientationInput() {
  76978. this.alphaCorrection = 1;
  76979. this.betaCorrection = 1;
  76980. this.gammaCorrection = 1;
  76981. this._alpha = 0;
  76982. this._gamma = 0;
  76983. this._dirty = false;
  76984. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  76985. }
  76986. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  76987. this.camera.attachControl(element, noPreventDefault);
  76988. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  76989. };
  76990. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  76991. if (evt.alpha !== null) {
  76992. this._alpha = +evt.alpha | 0;
  76993. }
  76994. if (evt.gamma !== null) {
  76995. this._gamma = +evt.gamma | 0;
  76996. }
  76997. this._dirty = true;
  76998. };
  76999. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  77000. if (this._dirty) {
  77001. this._dirty = false;
  77002. if (this._gamma < 0) {
  77003. this._gamma = 180 + this._gamma;
  77004. }
  77005. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  77006. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  77007. }
  77008. };
  77009. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  77010. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  77011. };
  77012. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  77013. return "ArcRotateCameraVRDeviceOrientationInput";
  77014. };
  77015. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  77016. return "VRDeviceOrientation";
  77017. };
  77018. return ArcRotateCameraVRDeviceOrientationInput;
  77019. }());
  77020. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  77021. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  77022. })(BABYLON || (BABYLON = {}));
  77023. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  77024. var BABYLON;
  77025. (function (BABYLON) {
  77026. var VRCameraMetrics = /** @class */ (function () {
  77027. function VRCameraMetrics() {
  77028. this.compensateDistortion = true;
  77029. }
  77030. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  77031. get: function () {
  77032. return this.hResolution / (2 * this.vResolution);
  77033. },
  77034. enumerable: true,
  77035. configurable: true
  77036. });
  77037. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  77038. get: function () {
  77039. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  77040. },
  77041. enumerable: true,
  77042. configurable: true
  77043. });
  77044. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  77045. get: function () {
  77046. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  77047. var h = (4 * meters) / this.hScreenSize;
  77048. return BABYLON.Matrix.Translation(h, 0, 0);
  77049. },
  77050. enumerable: true,
  77051. configurable: true
  77052. });
  77053. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  77054. get: function () {
  77055. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  77056. var h = (4 * meters) / this.hScreenSize;
  77057. return BABYLON.Matrix.Translation(-h, 0, 0);
  77058. },
  77059. enumerable: true,
  77060. configurable: true
  77061. });
  77062. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  77063. get: function () {
  77064. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  77065. },
  77066. enumerable: true,
  77067. configurable: true
  77068. });
  77069. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  77070. get: function () {
  77071. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  77072. },
  77073. enumerable: true,
  77074. configurable: true
  77075. });
  77076. VRCameraMetrics.GetDefault = function () {
  77077. var result = new VRCameraMetrics();
  77078. result.hResolution = 1280;
  77079. result.vResolution = 800;
  77080. result.hScreenSize = 0.149759993;
  77081. result.vScreenSize = 0.0935999975;
  77082. result.vScreenCenter = 0.0467999987;
  77083. result.eyeToScreenDistance = 0.0410000011;
  77084. result.lensSeparationDistance = 0.0635000020;
  77085. result.interpupillaryDistance = 0.0640000030;
  77086. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  77087. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  77088. result.postProcessScaleFactor = 1.714605507808412;
  77089. result.lensCenterOffset = 0.151976421;
  77090. return result;
  77091. };
  77092. return VRCameraMetrics;
  77093. }());
  77094. BABYLON.VRCameraMetrics = VRCameraMetrics;
  77095. })(BABYLON || (BABYLON = {}));
  77096. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  77097. var BABYLON;
  77098. (function (BABYLON) {
  77099. /**
  77100. * This represents a WebVR camera.
  77101. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  77102. * @example http://doc.babylonjs.com/how_to/webvr_camera
  77103. */
  77104. var WebVRFreeCamera = /** @class */ (function (_super) {
  77105. __extends(WebVRFreeCamera, _super);
  77106. /**
  77107. * Instantiates a WebVRFreeCamera.
  77108. * @param name The name of the WebVRFreeCamera
  77109. * @param position The starting anchor position for the camera
  77110. * @param scene The scene the camera belongs to
  77111. * @param webVROptions a set of customizable options for the webVRCamera
  77112. */
  77113. function WebVRFreeCamera(name, position, scene, webVROptions) {
  77114. if (webVROptions === void 0) { webVROptions = {}; }
  77115. var _this = _super.call(this, name, position, scene) || this;
  77116. _this.webVROptions = webVROptions;
  77117. /**
  77118. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  77119. */
  77120. _this._vrDevice = null;
  77121. /**
  77122. * The rawPose of the vrDevice.
  77123. */
  77124. _this.rawPose = null;
  77125. _this._specsVersion = "1.1";
  77126. _this._attached = false;
  77127. _this._descendants = [];
  77128. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  77129. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  77130. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  77131. _this._standingMatrix = null;
  77132. /**
  77133. * Represents device position in babylon space.
  77134. */
  77135. _this.devicePosition = BABYLON.Vector3.Zero();
  77136. /**
  77137. * Represents device rotation in babylon space.
  77138. */
  77139. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  77140. /**
  77141. * The scale of the device to be used when translating from device space to babylon space.
  77142. */
  77143. _this.deviceScaleFactor = 1;
  77144. _this._deviceToWorld = BABYLON.Matrix.Identity();
  77145. _this._worldToDevice = BABYLON.Matrix.Identity();
  77146. /**
  77147. * References to the webVR controllers for the vrDevice.
  77148. */
  77149. _this.controllers = [];
  77150. /**
  77151. * Emits an event when a controller is attached.
  77152. */
  77153. _this.onControllersAttachedObservable = new BABYLON.Observable();
  77154. /**
  77155. * Emits an event when a controller's mesh has been loaded;
  77156. */
  77157. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  77158. /**
  77159. * If the rig cameras be used as parent instead of this camera.
  77160. */
  77161. _this.rigParenting = true;
  77162. _this._defaultHeight = undefined;
  77163. _this._workingVector = BABYLON.Vector3.Zero();
  77164. _this._oneVector = BABYLON.Vector3.One();
  77165. _this._workingMatrix = BABYLON.Matrix.Identity();
  77166. _this._cache.position = BABYLON.Vector3.Zero();
  77167. if (webVROptions.defaultHeight) {
  77168. _this._defaultHeight = webVROptions.defaultHeight;
  77169. _this.position.y = _this._defaultHeight;
  77170. }
  77171. _this.minZ = 0.1;
  77172. //legacy support - the compensation boolean was removed.
  77173. if (arguments.length === 5) {
  77174. _this.webVROptions = arguments[4];
  77175. }
  77176. // default webVR options
  77177. if (_this.webVROptions.trackPosition == undefined) {
  77178. _this.webVROptions.trackPosition = true;
  77179. }
  77180. if (_this.webVROptions.controllerMeshes == undefined) {
  77181. _this.webVROptions.controllerMeshes = true;
  77182. }
  77183. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  77184. _this.webVROptions.defaultLightingOnControllers = true;
  77185. }
  77186. _this.rotationQuaternion = new BABYLON.Quaternion();
  77187. if (_this.webVROptions && _this.webVROptions.positionScale) {
  77188. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  77189. }
  77190. //enable VR
  77191. var engine = _this.getEngine();
  77192. _this._onVREnabled = function (success) { if (success) {
  77193. _this.initControllers();
  77194. } };
  77195. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  77196. engine.initWebVR().add(function (event) {
  77197. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  77198. return;
  77199. }
  77200. _this._vrDevice = event.vrDisplay;
  77201. //reset the rig parameters.
  77202. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  77203. if (_this._attached) {
  77204. _this.getEngine().enableVR();
  77205. }
  77206. });
  77207. if (typeof (VRFrameData) !== "undefined")
  77208. _this._frameData = new VRFrameData();
  77209. /**
  77210. * The idea behind the following lines:
  77211. * objects that have the camera as parent should actually have the rig cameras as a parent.
  77212. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  77213. * the second will not show it correctly.
  77214. *
  77215. * To solve this - each object that has the camera as parent will be added to a protected array.
  77216. * When the rig camera renders, it will take this array and set all of those to be its children.
  77217. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  77218. * Amazing!
  77219. */
  77220. scene.onBeforeCameraRenderObservable.add(function (camera) {
  77221. if (camera.parent === _this && _this.rigParenting) {
  77222. _this._descendants = _this.getDescendants(true, function (n) {
  77223. // don't take the cameras or the controllers!
  77224. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  77225. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  77226. return !isController && !isRigCamera;
  77227. });
  77228. _this._descendants.forEach(function (node) {
  77229. node.parent = camera;
  77230. });
  77231. }
  77232. });
  77233. scene.onAfterCameraRenderObservable.add(function (camera) {
  77234. if (camera.parent === _this && _this.rigParenting) {
  77235. _this._descendants.forEach(function (node) {
  77236. node.parent = _this;
  77237. });
  77238. }
  77239. });
  77240. return _this;
  77241. }
  77242. /**
  77243. * Gets the device distance from the ground.
  77244. * @returns the distance from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  77245. */
  77246. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  77247. if (this._standingMatrix && this._defaultHeight === undefined) {
  77248. // Add standing matrix offset to get real offset from ground in room
  77249. this._standingMatrix.getTranslationToRef(this._workingVector);
  77250. return this._deviceRoomPosition.y + this._workingVector.y;
  77251. }
  77252. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  77253. return this._defaultHeight || 0;
  77254. };
  77255. /**
  77256. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  77257. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  77258. */
  77259. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  77260. var _this = this;
  77261. if (callback === void 0) { callback = function (bool) { }; }
  77262. // Use standing matrix if available
  77263. if (!navigator || !navigator.getVRDisplays) {
  77264. callback(false);
  77265. }
  77266. else {
  77267. navigator.getVRDisplays().then(function (displays) {
  77268. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  77269. callback(false);
  77270. }
  77271. else {
  77272. _this._standingMatrix = new BABYLON.Matrix();
  77273. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  77274. if (!_this.getScene().useRightHandedSystem) {
  77275. [2, 6, 8, 9, 14].forEach(function (num) {
  77276. if (_this._standingMatrix) {
  77277. _this._standingMatrix.m[num] *= -1;
  77278. }
  77279. });
  77280. }
  77281. callback(true);
  77282. }
  77283. });
  77284. }
  77285. };
  77286. /**
  77287. * Disposes the camera
  77288. */
  77289. WebVRFreeCamera.prototype.dispose = function () {
  77290. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  77291. _super.prototype.dispose.call(this);
  77292. };
  77293. /**
  77294. * Gets a vrController by name.
  77295. * @param name The name of the controller to retreive
  77296. * @returns the controller matching the name specified or null if not found
  77297. */
  77298. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  77299. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  77300. var gp = _a[_i];
  77301. if (gp.hand === name) {
  77302. return gp;
  77303. }
  77304. }
  77305. return null;
  77306. };
  77307. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  77308. /**
  77309. * The controller corrisponding to the users left hand.
  77310. */
  77311. get: function () {
  77312. if (!this._leftController) {
  77313. this._leftController = this.getControllerByName("left");
  77314. }
  77315. return this._leftController;
  77316. },
  77317. enumerable: true,
  77318. configurable: true
  77319. });
  77320. ;
  77321. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  77322. /**
  77323. * The controller corrisponding to the users right hand.
  77324. */
  77325. get: function () {
  77326. if (!this._rightController) {
  77327. this._rightController = this.getControllerByName("right");
  77328. }
  77329. return this._rightController;
  77330. },
  77331. enumerable: true,
  77332. configurable: true
  77333. });
  77334. ;
  77335. /**
  77336. * Casts a ray forward from the vrCamera's gaze.
  77337. * @param length Length of the ray (default: 100)
  77338. * @returns the ray corrisponding to the gaze
  77339. */
  77340. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  77341. if (length === void 0) { length = 100; }
  77342. if (this.leftCamera) {
  77343. // Use left eye to avoid computation to compute center on every call
  77344. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  77345. }
  77346. else {
  77347. return _super.prototype.getForwardRay.call(this, length);
  77348. }
  77349. };
  77350. /**
  77351. * Updates the camera based on device's frame data
  77352. */
  77353. WebVRFreeCamera.prototype._checkInputs = function () {
  77354. if (this._vrDevice && this._vrDevice.isPresenting) {
  77355. this._vrDevice.getFrameData(this._frameData);
  77356. this.updateFromDevice(this._frameData.pose);
  77357. }
  77358. _super.prototype._checkInputs.call(this);
  77359. };
  77360. /**
  77361. * Updates the poseControlled values based on the input device pose.
  77362. * @param poseData Pose coming from the device
  77363. */
  77364. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  77365. if (poseData && poseData.orientation) {
  77366. this.rawPose = poseData;
  77367. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  77368. if (this.getScene().useRightHandedSystem) {
  77369. this._deviceRoomRotationQuaternion.z *= -1;
  77370. this._deviceRoomRotationQuaternion.w *= -1;
  77371. }
  77372. if (this.webVROptions.trackPosition && this.rawPose.position) {
  77373. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  77374. if (this.getScene().useRightHandedSystem) {
  77375. this._deviceRoomPosition.z *= -1;
  77376. }
  77377. }
  77378. }
  77379. };
  77380. /**
  77381. * WebVR's attach control will start broadcasting frames to the device.
  77382. * Note that in certain browsers (chrome for example) this function must be called
  77383. * within a user-interaction callback. Example:
  77384. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  77385. *
  77386. * @param element html element to attach the vrDevice to
  77387. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  77388. */
  77389. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  77390. _super.prototype.attachControl.call(this, element, noPreventDefault);
  77391. this._attached = true;
  77392. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  77393. if (this._vrDevice) {
  77394. this.getEngine().enableVR();
  77395. }
  77396. };
  77397. /**
  77398. * Detaches the camera from the html element and disables VR
  77399. *
  77400. * @param element html element to detach from
  77401. */
  77402. WebVRFreeCamera.prototype.detachControl = function (element) {
  77403. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  77404. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  77405. _super.prototype.detachControl.call(this, element);
  77406. this._attached = false;
  77407. this.getEngine().disableVR();
  77408. };
  77409. /**
  77410. * @returns the name of this class
  77411. */
  77412. WebVRFreeCamera.prototype.getClassName = function () {
  77413. return "WebVRFreeCamera";
  77414. };
  77415. /**
  77416. * Calls resetPose on the vrDisplay
  77417. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  77418. */
  77419. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  77420. //uses the vrDisplay's "resetPose()".
  77421. //pitch and roll won't be affected.
  77422. this._vrDevice.resetPose();
  77423. };
  77424. /**
  77425. * Updates the rig cameras (left and right eye)
  77426. */
  77427. WebVRFreeCamera.prototype._updateRigCameras = function () {
  77428. var camLeft = this._rigCameras[0];
  77429. var camRight = this._rigCameras[1];
  77430. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  77431. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  77432. camLeft.position.copyFrom(this._deviceRoomPosition);
  77433. camRight.position.copyFrom(this._deviceRoomPosition);
  77434. };
  77435. /**
  77436. * Updates the cached values of the camera
  77437. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  77438. */
  77439. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  77440. var _this = this;
  77441. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  77442. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  77443. if (!this.updateCacheCalled) {
  77444. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  77445. this.updateCacheCalled = true;
  77446. this.update();
  77447. }
  77448. // Set working vector to the device position in room space rotated by the new rotation
  77449. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  77450. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  77451. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  77452. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  77453. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  77454. // Add translation from anchor position
  77455. this._deviceToWorld.getTranslationToRef(this._workingVector);
  77456. this._workingVector.addInPlace(this.position);
  77457. this._workingVector.subtractInPlace(this._cache.position);
  77458. this._deviceToWorld.setTranslation(this._workingVector);
  77459. // Set an inverted matrix to be used when updating the camera
  77460. this._deviceToWorld.invertToRef(this._worldToDevice);
  77461. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  77462. this.controllers.forEach(function (controller) {
  77463. controller._deviceToWorld = _this._deviceToWorld;
  77464. controller.update();
  77465. });
  77466. }
  77467. if (!ignoreParentClass) {
  77468. _super.prototype._updateCache.call(this);
  77469. }
  77470. this.updateCacheCalled = false;
  77471. };
  77472. /**
  77473. * Updates the current device position and rotation in the babylon world
  77474. */
  77475. WebVRFreeCamera.prototype.update = function () {
  77476. // Get current device position in babylon world
  77477. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  77478. // Get current device rotation in babylon world
  77479. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  77480. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  77481. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  77482. _super.prototype.update.call(this);
  77483. };
  77484. /**
  77485. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  77486. * @returns an identity matrix
  77487. */
  77488. WebVRFreeCamera.prototype._getViewMatrix = function () {
  77489. return BABYLON.Matrix.Identity();
  77490. };
  77491. /**
  77492. * This function is called by the two RIG cameras.
  77493. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  77494. */
  77495. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  77496. var _this = this;
  77497. //WebVR 1.1
  77498. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  77499. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  77500. if (!this.getScene().useRightHandedSystem) {
  77501. [2, 6, 8, 9, 14].forEach(function (num) {
  77502. _this._webvrViewMatrix.m[num] *= -1;
  77503. });
  77504. }
  77505. // update the camera rotation matrix
  77506. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  77507. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  77508. // Computing target and final matrix
  77509. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  77510. var parentCamera = this._cameraRigParams["parentCamera"];
  77511. // should the view matrix be updated with scale and position offset?
  77512. if (parentCamera.deviceScaleFactor !== 1) {
  77513. this._webvrViewMatrix.invert();
  77514. // scale the position, if set
  77515. if (parentCamera.deviceScaleFactor) {
  77516. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  77517. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  77518. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  77519. }
  77520. this._webvrViewMatrix.invert();
  77521. }
  77522. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  77523. return this._webvrViewMatrix;
  77524. };
  77525. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  77526. var _this = this;
  77527. var parentCamera = this.parent;
  77528. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  77529. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  77530. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  77531. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  77532. //babylon compatible matrix
  77533. if (!this.getScene().useRightHandedSystem) {
  77534. [8, 9, 10, 11].forEach(function (num) {
  77535. _this._projectionMatrix.m[num] *= -1;
  77536. });
  77537. }
  77538. return this._projectionMatrix;
  77539. };
  77540. /**
  77541. * Initializes the controllers and their meshes
  77542. */
  77543. WebVRFreeCamera.prototype.initControllers = function () {
  77544. var _this = this;
  77545. this.controllers = [];
  77546. var manager = this.getScene().gamepadManager;
  77547. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  77548. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  77549. var webVrController = gamepad;
  77550. if (webVrController.defaultModel) {
  77551. webVrController.defaultModel.setEnabled(false);
  77552. }
  77553. if (webVrController.hand === "right") {
  77554. _this._rightController = null;
  77555. }
  77556. if (webVrController.hand === "left") {
  77557. _this._rightController = null;
  77558. }
  77559. var controllerIndex = _this.controllers.indexOf(webVrController);
  77560. if (controllerIndex !== -1) {
  77561. _this.controllers.splice(controllerIndex, 1);
  77562. }
  77563. }
  77564. });
  77565. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  77566. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  77567. var webVrController_1 = gamepad;
  77568. webVrController_1._deviceToWorld = _this._deviceToWorld;
  77569. if (_this.webVROptions.controllerMeshes) {
  77570. if (webVrController_1.defaultModel) {
  77571. webVrController_1.defaultModel.setEnabled(true);
  77572. }
  77573. else {
  77574. // Load the meshes
  77575. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  77576. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  77577. if (_this.webVROptions.defaultLightingOnControllers) {
  77578. if (!_this._lightOnControllers) {
  77579. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  77580. }
  77581. var activateLightOnSubMeshes_1 = function (mesh, light) {
  77582. var children = mesh.getChildren();
  77583. if (children.length !== 0) {
  77584. children.forEach(function (mesh) {
  77585. light.includedOnlyMeshes.push(mesh);
  77586. activateLightOnSubMeshes_1(mesh, light);
  77587. });
  77588. }
  77589. };
  77590. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  77591. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  77592. }
  77593. });
  77594. }
  77595. }
  77596. webVrController_1.attachToPoseControlledCamera(_this);
  77597. // since this is async - sanity check. Is the controller already stored?
  77598. if (_this.controllers.indexOf(webVrController_1) === -1) {
  77599. //add to the controllers array
  77600. _this.controllers.push(webVrController_1);
  77601. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  77602. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  77603. // So we're overriding setting left & right manually to be sure
  77604. var firstViveWandDetected = false;
  77605. for (var i = 0; i < _this.controllers.length; i++) {
  77606. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  77607. if (!firstViveWandDetected) {
  77608. firstViveWandDetected = true;
  77609. _this.controllers[i].hand = "left";
  77610. }
  77611. else {
  77612. _this.controllers[i].hand = "right";
  77613. }
  77614. }
  77615. }
  77616. //did we find enough controllers? Great! let the developer know.
  77617. if (_this.controllers.length >= 2) {
  77618. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  77619. }
  77620. }
  77621. }
  77622. });
  77623. };
  77624. return WebVRFreeCamera;
  77625. }(BABYLON.FreeCamera));
  77626. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  77627. })(BABYLON || (BABYLON = {}));
  77628. //# sourceMappingURL=babylon.webVRCamera.js.map
  77629. var BABYLON;
  77630. (function (BABYLON) {
  77631. // We're mainly based on the logic defined into the FreeCamera code
  77632. /**
  77633. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  77634. * being tilted forward or back and left or right.
  77635. */
  77636. var DeviceOrientationCamera = /** @class */ (function (_super) {
  77637. __extends(DeviceOrientationCamera, _super);
  77638. /**
  77639. * Creates a new device orientation camera. @see DeviceOrientationCamera
  77640. * @param name The name of the camera
  77641. * @param position The start position camera
  77642. * @param scene The scene the camera belongs to
  77643. */
  77644. function DeviceOrientationCamera(name, position, scene) {
  77645. var _this = _super.call(this, name, position, scene) || this;
  77646. _this._quaternionCache = new BABYLON.Quaternion();
  77647. _this.inputs.addDeviceOrientation();
  77648. return _this;
  77649. }
  77650. /**
  77651. * Gets the current instance class name ("DeviceOrientationCamera").
  77652. * This helps avoiding instanceof at run time.
  77653. * @returns the class name
  77654. */
  77655. DeviceOrientationCamera.prototype.getClassName = function () {
  77656. return "DeviceOrientationCamera";
  77657. };
  77658. /**
  77659. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  77660. */
  77661. DeviceOrientationCamera.prototype._checkInputs = function () {
  77662. _super.prototype._checkInputs.call(this);
  77663. this._quaternionCache.copyFrom(this.rotationQuaternion);
  77664. if (this._initialQuaternion) {
  77665. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  77666. }
  77667. };
  77668. /**
  77669. * Reset the camera to its default orientation on the specified axis only.
  77670. * @param axis The axis to reset
  77671. */
  77672. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  77673. var _this = this;
  77674. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  77675. //can only work if this camera has a rotation quaternion already.
  77676. if (!this.rotationQuaternion)
  77677. return;
  77678. if (!this._initialQuaternion) {
  77679. this._initialQuaternion = new BABYLON.Quaternion();
  77680. }
  77681. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  77682. ['x', 'y', 'z'].forEach(function (axisName) {
  77683. if (!axis[axisName]) {
  77684. _this._initialQuaternion[axisName] = 0;
  77685. }
  77686. else {
  77687. _this._initialQuaternion[axisName] *= -1;
  77688. }
  77689. });
  77690. this._initialQuaternion.normalize();
  77691. //force rotation update
  77692. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  77693. };
  77694. return DeviceOrientationCamera;
  77695. }(BABYLON.FreeCamera));
  77696. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  77697. })(BABYLON || (BABYLON = {}));
  77698. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  77699. var BABYLON;
  77700. (function (BABYLON) {
  77701. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  77702. __extends(VRDeviceOrientationFreeCamera, _super);
  77703. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  77704. if (compensateDistortion === void 0) { compensateDistortion = true; }
  77705. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  77706. var _this = _super.call(this, name, position, scene) || this;
  77707. vrCameraMetrics.compensateDistortion = compensateDistortion;
  77708. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  77709. return _this;
  77710. }
  77711. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  77712. return "VRDeviceOrientationFreeCamera";
  77713. };
  77714. return VRDeviceOrientationFreeCamera;
  77715. }(BABYLON.DeviceOrientationCamera));
  77716. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  77717. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  77718. __extends(VRDeviceOrientationGamepadCamera, _super);
  77719. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  77720. if (compensateDistortion === void 0) { compensateDistortion = true; }
  77721. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  77722. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  77723. _this.inputs.addGamepad();
  77724. return _this;
  77725. }
  77726. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  77727. return "VRDeviceOrientationGamepadCamera";
  77728. };
  77729. return VRDeviceOrientationGamepadCamera;
  77730. }(VRDeviceOrientationFreeCamera));
  77731. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  77732. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  77733. __extends(VRDeviceOrientationArcRotateCamera, _super);
  77734. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  77735. if (compensateDistortion === void 0) { compensateDistortion = true; }
  77736. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  77737. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  77738. vrCameraMetrics.compensateDistortion = compensateDistortion;
  77739. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  77740. _this.inputs.addVRDeviceOrientation();
  77741. return _this;
  77742. }
  77743. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  77744. return "VRDeviceOrientationArcRotateCamera";
  77745. };
  77746. return VRDeviceOrientationArcRotateCamera;
  77747. }(BABYLON.ArcRotateCamera));
  77748. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  77749. })(BABYLON || (BABYLON = {}));
  77750. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  77751. var BABYLON;
  77752. (function (BABYLON) {
  77753. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  77754. __extends(AnaglyphFreeCamera, _super);
  77755. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  77756. var _this = _super.call(this, name, position, scene) || this;
  77757. _this.interaxialDistance = interaxialDistance;
  77758. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  77759. return _this;
  77760. }
  77761. AnaglyphFreeCamera.prototype.getClassName = function () {
  77762. return "AnaglyphFreeCamera";
  77763. };
  77764. return AnaglyphFreeCamera;
  77765. }(BABYLON.FreeCamera));
  77766. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  77767. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  77768. __extends(AnaglyphArcRotateCamera, _super);
  77769. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  77770. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  77771. _this.interaxialDistance = interaxialDistance;
  77772. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  77773. return _this;
  77774. }
  77775. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  77776. return "AnaglyphArcRotateCamera";
  77777. };
  77778. return AnaglyphArcRotateCamera;
  77779. }(BABYLON.ArcRotateCamera));
  77780. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  77781. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  77782. __extends(AnaglyphGamepadCamera, _super);
  77783. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  77784. var _this = _super.call(this, name, position, scene) || this;
  77785. _this.interaxialDistance = interaxialDistance;
  77786. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  77787. return _this;
  77788. }
  77789. AnaglyphGamepadCamera.prototype.getClassName = function () {
  77790. return "AnaglyphGamepadCamera";
  77791. };
  77792. return AnaglyphGamepadCamera;
  77793. }(BABYLON.GamepadCamera));
  77794. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  77795. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  77796. __extends(AnaglyphUniversalCamera, _super);
  77797. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  77798. var _this = _super.call(this, name, position, scene) || this;
  77799. _this.interaxialDistance = interaxialDistance;
  77800. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  77801. return _this;
  77802. }
  77803. AnaglyphUniversalCamera.prototype.getClassName = function () {
  77804. return "AnaglyphUniversalCamera";
  77805. };
  77806. return AnaglyphUniversalCamera;
  77807. }(BABYLON.UniversalCamera));
  77808. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  77809. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  77810. __extends(StereoscopicFreeCamera, _super);
  77811. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  77812. var _this = _super.call(this, name, position, scene) || this;
  77813. _this.interaxialDistance = interaxialDistance;
  77814. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  77815. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  77816. return _this;
  77817. }
  77818. StereoscopicFreeCamera.prototype.getClassName = function () {
  77819. return "StereoscopicFreeCamera";
  77820. };
  77821. return StereoscopicFreeCamera;
  77822. }(BABYLON.FreeCamera));
  77823. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  77824. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  77825. __extends(StereoscopicArcRotateCamera, _super);
  77826. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  77827. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  77828. _this.interaxialDistance = interaxialDistance;
  77829. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  77830. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  77831. return _this;
  77832. }
  77833. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  77834. return "StereoscopicArcRotateCamera";
  77835. };
  77836. return StereoscopicArcRotateCamera;
  77837. }(BABYLON.ArcRotateCamera));
  77838. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  77839. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  77840. __extends(StereoscopicGamepadCamera, _super);
  77841. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  77842. var _this = _super.call(this, name, position, scene) || this;
  77843. _this.interaxialDistance = interaxialDistance;
  77844. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  77845. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  77846. return _this;
  77847. }
  77848. StereoscopicGamepadCamera.prototype.getClassName = function () {
  77849. return "StereoscopicGamepadCamera";
  77850. };
  77851. return StereoscopicGamepadCamera;
  77852. }(BABYLON.GamepadCamera));
  77853. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  77854. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  77855. __extends(StereoscopicUniversalCamera, _super);
  77856. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  77857. var _this = _super.call(this, name, position, scene) || this;
  77858. _this.interaxialDistance = interaxialDistance;
  77859. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  77860. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  77861. return _this;
  77862. }
  77863. StereoscopicUniversalCamera.prototype.getClassName = function () {
  77864. return "StereoscopicUniversalCamera";
  77865. };
  77866. return StereoscopicUniversalCamera;
  77867. }(BABYLON.UniversalCamera));
  77868. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  77869. })(BABYLON || (BABYLON = {}));
  77870. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  77871. var BABYLON;
  77872. (function (BABYLON) {
  77873. /**
  77874. * Helps to quickly add VR support to an existing scene.
  77875. * See http://doc.babylonjs.com/how_to/webvr_helper
  77876. */
  77877. var VRExperienceHelper = /** @class */ (function () {
  77878. /**
  77879. * Instantiates a VRExperienceHelper.
  77880. * Helps to quickly add VR support to an existing scene.
  77881. * @param scene The scene the VRExperienceHelper belongs to.
  77882. * @param webVROptions Options to modify the vr experience helper's behavior.
  77883. */
  77884. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  77885. if (webVROptions === void 0) { webVROptions = {}; }
  77886. var _this = this;
  77887. this.webVROptions = webVROptions;
  77888. // Can the system support WebVR, even if a headset isn't plugged in?
  77889. this._webVRsupported = false;
  77890. // If WebVR is supported, is a headset plugged in and are we ready to present?
  77891. this._webVRready = false;
  77892. // Are we waiting for the requestPresent callback to complete?
  77893. this._webVRrequesting = false;
  77894. // Are we presenting to the headset right now?
  77895. this._webVRpresenting = false;
  77896. // Are we presenting in the fullscreen fallback?
  77897. this._fullscreenVRpresenting = false;
  77898. /**
  77899. * Observable raised when entering VR.
  77900. */
  77901. this.onEnteringVRObservable = new BABYLON.Observable();
  77902. /**
  77903. * Observable raised when exiting VR.
  77904. */
  77905. this.onExitingVRObservable = new BABYLON.Observable();
  77906. /**
  77907. * Observable raised when controller mesh is loaded.
  77908. */
  77909. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  77910. this._useCustomVRButton = false;
  77911. this._teleportationRequested = false;
  77912. this._teleportationEnabledOnLeftController = false;
  77913. this._teleportationEnabledOnRightController = false;
  77914. this._interactionsEnabledOnLeftController = false;
  77915. this._interactionsEnabledOnRightController = false;
  77916. this._leftControllerReady = false;
  77917. this._rightControllerReady = false;
  77918. this._floorMeshesCollection = [];
  77919. this._teleportationAllowed = false;
  77920. this._rotationAllowed = true;
  77921. this._teleportationRequestInitiated = false;
  77922. this._teleportationBackRequestInitiated = false;
  77923. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  77924. this._rotationRightAsked = false;
  77925. this._rotationLeftAsked = false;
  77926. this._isDefaultTeleportationTarget = true;
  77927. this._teleportationFillColor = "#444444";
  77928. this._teleportationBorderColor = "#FFFFFF";
  77929. this._rotationAngle = 0;
  77930. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  77931. this._padSensibilityUp = 0.65;
  77932. this._padSensibilityDown = 0.35;
  77933. /**
  77934. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  77935. */
  77936. this.onNewMeshSelected = new BABYLON.Observable();
  77937. /**
  77938. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  77939. */
  77940. this.onNewMeshPicked = new BABYLON.Observable();
  77941. /**
  77942. * Observable raised before camera teleportation
  77943. */
  77944. this.onBeforeCameraTeleport = new BABYLON.Observable();
  77945. /**
  77946. * Observable raised after camera teleportation
  77947. */
  77948. this.onAfterCameraTeleport = new BABYLON.Observable();
  77949. /**
  77950. * Observable raised when current selected mesh gets unselected
  77951. */
  77952. this.onSelectedMeshUnselected = new BABYLON.Observable();
  77953. /**
  77954. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  77955. */
  77956. this.teleportationEnabled = true;
  77957. this._pointerDownOnMeshAsked = false;
  77958. this._isActionableMesh = false;
  77959. this._teleportationInitialized = false;
  77960. this._interactionsEnabled = false;
  77961. this._interactionsRequested = false;
  77962. this._displayGaze = true;
  77963. this._displayLaserPointer = true;
  77964. this._dpadPressed = true;
  77965. this._onResize = function () {
  77966. _this.moveButtonToBottomRight();
  77967. if (_this._fullscreenVRpresenting && _this._webVRready) {
  77968. _this.exitVR();
  77969. }
  77970. };
  77971. this._onFullscreenChange = function () {
  77972. if (document.fullscreen !== undefined) {
  77973. _this._fullscreenVRpresenting = document.fullscreen;
  77974. }
  77975. else if (document.mozFullScreen !== undefined) {
  77976. _this._fullscreenVRpresenting = document.mozFullScreen;
  77977. }
  77978. else if (document.webkitIsFullScreen !== undefined) {
  77979. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  77980. }
  77981. else if (document.msIsFullScreen !== undefined) {
  77982. _this._fullscreenVRpresenting = document.msIsFullScreen;
  77983. }
  77984. if (!_this._fullscreenVRpresenting && _this._canvas) {
  77985. _this.exitVR();
  77986. if (!_this._useCustomVRButton) {
  77987. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  77988. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  77989. }
  77990. }
  77991. };
  77992. this.beforeRender = function () {
  77993. _this._castRayAndSelectObject();
  77994. };
  77995. this._onNewGamepadConnected = function (gamepad) {
  77996. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  77997. if (gamepad.leftStick) {
  77998. gamepad.onleftstickchanged(function (stickValues) {
  77999. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  78000. // Listening to classic/xbox gamepad only if no VR controller is active
  78001. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  78002. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  78003. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  78004. _this._checkTeleportWithRay(stickValues);
  78005. _this._checkTeleportBackwards(stickValues);
  78006. }
  78007. }
  78008. });
  78009. }
  78010. if (gamepad.rightStick) {
  78011. gamepad.onrightstickchanged(function (stickValues) {
  78012. if (_this._teleportationInitialized) {
  78013. _this._checkRotate(stickValues);
  78014. }
  78015. });
  78016. }
  78017. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  78018. gamepad.onbuttondown(function (buttonPressed) {
  78019. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  78020. _this._selectionPointerDown();
  78021. }
  78022. });
  78023. gamepad.onbuttonup(function (buttonPressed) {
  78024. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  78025. _this._selectionPointerUp();
  78026. }
  78027. });
  78028. }
  78029. }
  78030. else {
  78031. var webVRController = gamepad;
  78032. _this._tryEnableInteractionOnController(webVRController);
  78033. }
  78034. };
  78035. // 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
  78036. this._tryEnableInteractionOnController = function (webVRController) {
  78037. if (webVRController.hand === "left") {
  78038. _this._leftControllerReady = true;
  78039. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  78040. _this._enableInteractionOnController(webVRController);
  78041. }
  78042. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  78043. _this._enableTeleportationOnController(webVRController);
  78044. }
  78045. }
  78046. if (webVRController.hand === "right") {
  78047. _this._rightControllerReady = true;
  78048. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  78049. _this._enableInteractionOnController(webVRController);
  78050. }
  78051. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  78052. _this._enableTeleportationOnController(webVRController);
  78053. }
  78054. }
  78055. };
  78056. this._onNewGamepadDisconnected = function (gamepad) {
  78057. if (gamepad instanceof BABYLON.WebVRController) {
  78058. if (gamepad.hand === "left") {
  78059. _this._interactionsEnabledOnLeftController = false;
  78060. _this._teleportationEnabledOnLeftController = false;
  78061. _this._leftControllerReady = false;
  78062. if (_this._leftLaserPointer) {
  78063. _this._leftLaserPointer.dispose();
  78064. }
  78065. }
  78066. if (gamepad.hand === "right") {
  78067. _this._interactionsEnabledOnRightController = false;
  78068. _this._teleportationEnabledOnRightController = false;
  78069. _this._rightControllerReady = false;
  78070. if (_this._rightLaserPointer) {
  78071. _this._rightLaserPointer.dispose();
  78072. }
  78073. }
  78074. }
  78075. };
  78076. this._workingVector = BABYLON.Vector3.Zero();
  78077. this._workingQuaternion = BABYLON.Quaternion.Identity();
  78078. this._workingMatrix = BABYLON.Matrix.Identity();
  78079. this._scene = scene;
  78080. this._canvas = scene.getEngine().getRenderingCanvas();
  78081. // Parse options
  78082. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  78083. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  78084. }
  78085. if (webVROptions.createDeviceOrientationCamera === undefined) {
  78086. webVROptions.createDeviceOrientationCamera = true;
  78087. }
  78088. if (webVROptions.defaultHeight === undefined) {
  78089. webVROptions.defaultHeight = 1.7;
  78090. }
  78091. if (webVROptions.useCustomVRButton) {
  78092. this._useCustomVRButton = true;
  78093. if (webVROptions.customVRButton) {
  78094. this._btnVR = webVROptions.customVRButton;
  78095. }
  78096. }
  78097. if (webVROptions.rayLength) {
  78098. this._rayLength = webVROptions.rayLength;
  78099. }
  78100. this._defaultHeight = webVROptions.defaultHeight;
  78101. // Set position
  78102. if (this._scene.activeCamera) {
  78103. this._position = this._scene.activeCamera.position.clone();
  78104. }
  78105. else {
  78106. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  78107. }
  78108. // Set non-vr camera
  78109. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  78110. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  78111. // Copy data from existing camera
  78112. if (this._scene.activeCamera) {
  78113. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  78114. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  78115. // Set rotation from previous camera
  78116. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  78117. var targetCamera = this._scene.activeCamera;
  78118. if (targetCamera.rotationQuaternion) {
  78119. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  78120. }
  78121. else {
  78122. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  78123. }
  78124. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  78125. }
  78126. }
  78127. this._scene.activeCamera = this._deviceOrientationCamera;
  78128. if (this._canvas) {
  78129. this._scene.activeCamera.attachControl(this._canvas);
  78130. }
  78131. }
  78132. else {
  78133. this._existingCamera = this._scene.activeCamera;
  78134. }
  78135. // Create VR cameras
  78136. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  78137. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  78138. }
  78139. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  78140. this._webVRCamera.useStandingMatrix();
  78141. // Create default button
  78142. if (!this._useCustomVRButton) {
  78143. this._btnVR = document.createElement("BUTTON");
  78144. this._btnVR.className = "babylonVRicon";
  78145. this._btnVR.id = "babylonVRiconbtn";
  78146. this._btnVR.title = "Click to switch to VR";
  78147. 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) }";
  78148. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  78149. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  78150. // css += ".babylonVRicon.vrdisplaysupported { }";
  78151. // css += ".babylonVRicon.vrdisplayready { }";
  78152. // css += ".babylonVRicon.vrdisplayrequesting { }";
  78153. var style = document.createElement('style');
  78154. style.appendChild(document.createTextNode(css));
  78155. document.getElementsByTagName('head')[0].appendChild(style);
  78156. this.moveButtonToBottomRight();
  78157. }
  78158. // VR button click event
  78159. if (this._btnVR) {
  78160. this._btnVR.addEventListener("click", function () {
  78161. if (!_this.isInVRMode) {
  78162. _this.enterVR();
  78163. }
  78164. else {
  78165. _this.exitVR();
  78166. }
  78167. });
  78168. }
  78169. // Window events
  78170. window.addEventListener("resize", this._onResize);
  78171. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  78172. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  78173. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  78174. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  78175. // Display vr button when headset is connected
  78176. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  78177. this.displayVRButton();
  78178. }
  78179. else {
  78180. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  78181. if (e.vrDisplay) {
  78182. _this.displayVRButton();
  78183. }
  78184. });
  78185. }
  78186. // Exiting VR mode using 'ESC' key on desktop
  78187. this._onKeyDown = function (event) {
  78188. if (event.keyCode === 27 && _this.isInVRMode) {
  78189. _this.exitVR();
  78190. }
  78191. };
  78192. document.addEventListener("keydown", this._onKeyDown);
  78193. // Exiting VR mode double tapping the touch screen
  78194. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  78195. if (_this.isInVRMode) {
  78196. _this.exitVR();
  78197. if (_this._fullscreenVRpresenting) {
  78198. _this._scene.getEngine().switchFullscreen(true);
  78199. }
  78200. }
  78201. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  78202. // Listen for WebVR display changes
  78203. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  78204. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  78205. this._onVRRequestPresentStart = function () {
  78206. _this._webVRrequesting = true;
  78207. _this.updateButtonVisibility();
  78208. };
  78209. this._onVRRequestPresentComplete = function (success) {
  78210. _this._webVRrequesting = false;
  78211. _this.updateButtonVisibility();
  78212. };
  78213. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  78214. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  78215. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  78216. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  78217. scene.onDisposeObservable.add(function () {
  78218. _this.dispose();
  78219. });
  78220. // Gamepad connection events
  78221. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  78222. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  78223. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  78224. this.updateButtonVisibility();
  78225. //create easing functions
  78226. this._circleEase = new BABYLON.CircleEase();
  78227. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  78228. }
  78229. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  78230. /** Return this.onEnteringVRObservable
  78231. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  78232. */
  78233. get: function () {
  78234. return this.onEnteringVRObservable;
  78235. },
  78236. enumerable: true,
  78237. configurable: true
  78238. });
  78239. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  78240. /** Return this.onExitingVRObservable
  78241. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  78242. */
  78243. get: function () {
  78244. return this.onExitingVRObservable;
  78245. },
  78246. enumerable: true,
  78247. configurable: true
  78248. });
  78249. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  78250. /** Return this.onControllerMeshLoadedObservable
  78251. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  78252. */
  78253. get: function () {
  78254. return this.onControllerMeshLoadedObservable;
  78255. },
  78256. enumerable: true,
  78257. configurable: true
  78258. });
  78259. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  78260. /**
  78261. * The mesh used to display where the user is going to teleport.
  78262. */
  78263. get: function () {
  78264. return this._teleportationTarget;
  78265. },
  78266. /**
  78267. * Sets the mesh to be used to display where the user is going to teleport.
  78268. */
  78269. set: function (value) {
  78270. if (value) {
  78271. value.name = "teleportationTarget";
  78272. this._isDefaultTeleportationTarget = false;
  78273. this._teleportationTarget = value;
  78274. }
  78275. },
  78276. enumerable: true,
  78277. configurable: true
  78278. });
  78279. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  78280. /**
  78281. * If the ray of the gaze should be displayed.
  78282. */
  78283. get: function () {
  78284. return this._displayGaze;
  78285. },
  78286. /**
  78287. * Sets if the ray of the gaze should be displayed.
  78288. */
  78289. set: function (value) {
  78290. this._displayGaze = value;
  78291. if (!value) {
  78292. this._gazeTracker.isVisible = false;
  78293. }
  78294. },
  78295. enumerable: true,
  78296. configurable: true
  78297. });
  78298. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  78299. /**
  78300. * If the ray of the LaserPointer should be displayed.
  78301. */
  78302. get: function () {
  78303. return this._displayLaserPointer;
  78304. },
  78305. /**
  78306. * Sets if the ray of the LaserPointer should be displayed.
  78307. */
  78308. set: function (value) {
  78309. this._displayLaserPointer = value;
  78310. if (!value) {
  78311. if (this._rightLaserPointer) {
  78312. this._rightLaserPointer.isVisible = false;
  78313. }
  78314. if (this._leftLaserPointer) {
  78315. this._leftLaserPointer.isVisible = false;
  78316. }
  78317. }
  78318. else {
  78319. if (this._rightLaserPointer) {
  78320. this._rightLaserPointer.isVisible = true;
  78321. }
  78322. else if (this._leftLaserPointer) {
  78323. this._leftLaserPointer.isVisible = true;
  78324. }
  78325. }
  78326. },
  78327. enumerable: true,
  78328. configurable: true
  78329. });
  78330. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  78331. /**
  78332. * The deviceOrientationCamera used as the camera when not in VR.
  78333. */
  78334. get: function () {
  78335. return this._deviceOrientationCamera;
  78336. },
  78337. enumerable: true,
  78338. configurable: true
  78339. });
  78340. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  78341. /**
  78342. * Based on the current WebVR support, returns the current VR camera used.
  78343. */
  78344. get: function () {
  78345. if (this._webVRready) {
  78346. return this._webVRCamera;
  78347. }
  78348. else {
  78349. return this._scene.activeCamera;
  78350. }
  78351. },
  78352. enumerable: true,
  78353. configurable: true
  78354. });
  78355. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  78356. /**
  78357. * The webVRCamera which is used when in VR.
  78358. */
  78359. get: function () {
  78360. return this._webVRCamera;
  78361. },
  78362. enumerable: true,
  78363. configurable: true
  78364. });
  78365. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  78366. /**
  78367. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  78368. */
  78369. get: function () {
  78370. return this._vrDeviceOrientationCamera;
  78371. },
  78372. enumerable: true,
  78373. configurable: true
  78374. });
  78375. // Raised when one of the controller has loaded successfully its associated default mesh
  78376. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  78377. this._tryEnableInteractionOnController(webVRController);
  78378. try {
  78379. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  78380. }
  78381. catch (err) {
  78382. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  78383. }
  78384. };
  78385. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  78386. /**
  78387. * Gets a value indicating if we are currently in VR mode.
  78388. */
  78389. get: function () {
  78390. return this._webVRpresenting || this._fullscreenVRpresenting;
  78391. },
  78392. enumerable: true,
  78393. configurable: true
  78394. });
  78395. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  78396. var vrDisplay = this._scene.getEngine().getVRDevice();
  78397. if (vrDisplay) {
  78398. var wasPresenting = this._webVRpresenting;
  78399. // A VR display is connected
  78400. this._webVRpresenting = vrDisplay.isPresenting;
  78401. if (wasPresenting && !this._webVRpresenting)
  78402. this.exitVR();
  78403. }
  78404. else {
  78405. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  78406. }
  78407. this.updateButtonVisibility();
  78408. };
  78409. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  78410. this._webVRsupported = eventArgs.vrSupported;
  78411. this._webVRready = !!eventArgs.vrDisplay;
  78412. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  78413. this.updateButtonVisibility();
  78414. };
  78415. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  78416. if (this._canvas && !this._useCustomVRButton) {
  78417. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  78418. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  78419. }
  78420. };
  78421. VRExperienceHelper.prototype.displayVRButton = function () {
  78422. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  78423. document.body.appendChild(this._btnVR);
  78424. this._btnVRDisplayed = true;
  78425. }
  78426. };
  78427. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  78428. if (!this._btnVR || this._useCustomVRButton) {
  78429. return;
  78430. }
  78431. this._btnVR.className = "babylonVRicon";
  78432. if (this.isInVRMode) {
  78433. this._btnVR.className += " vrdisplaypresenting";
  78434. }
  78435. else {
  78436. if (this._webVRready)
  78437. this._btnVR.className += " vrdisplayready";
  78438. if (this._webVRsupported)
  78439. this._btnVR.className += " vrdisplaysupported";
  78440. if (this._webVRrequesting)
  78441. this._btnVR.className += " vrdisplayrequesting";
  78442. }
  78443. };
  78444. /**
  78445. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  78446. * Otherwise, will use the fullscreen API.
  78447. */
  78448. VRExperienceHelper.prototype.enterVR = function () {
  78449. if (this.onEnteringVRObservable) {
  78450. try {
  78451. this.onEnteringVRObservable.notifyObservers(this);
  78452. }
  78453. catch (err) {
  78454. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  78455. }
  78456. }
  78457. if (this._scene.activeCamera) {
  78458. this._position = this._scene.activeCamera.position.clone();
  78459. // make sure that we return to the last active camera
  78460. this._existingCamera = this._scene.activeCamera;
  78461. }
  78462. if (this._webVRrequesting)
  78463. return;
  78464. // If WebVR is supported and a headset is connected
  78465. if (this._webVRready) {
  78466. if (!this._webVRpresenting) {
  78467. this._webVRCamera.position = this._position;
  78468. this._scene.activeCamera = this._webVRCamera;
  78469. }
  78470. }
  78471. else if (this._vrDeviceOrientationCamera) {
  78472. this._vrDeviceOrientationCamera.position = this._position;
  78473. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  78474. this._scene.getEngine().switchFullscreen(true);
  78475. this.updateButtonVisibility();
  78476. }
  78477. if (this._scene.activeCamera && this._canvas) {
  78478. this._scene.activeCamera.attachControl(this._canvas);
  78479. }
  78480. if (this._interactionsEnabled) {
  78481. this._scene.registerBeforeRender(this.beforeRender);
  78482. }
  78483. };
  78484. /**
  78485. * Attempt to exit VR, or fullscreen.
  78486. */
  78487. VRExperienceHelper.prototype.exitVR = function () {
  78488. if (this.onExitingVRObservable) {
  78489. try {
  78490. this.onExitingVRObservable.notifyObservers(this);
  78491. }
  78492. catch (err) {
  78493. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  78494. }
  78495. }
  78496. if (this._webVRpresenting) {
  78497. this._scene.getEngine().disableVR();
  78498. }
  78499. if (this._scene.activeCamera) {
  78500. this._position = this._scene.activeCamera.position.clone();
  78501. }
  78502. if (this._deviceOrientationCamera) {
  78503. this._deviceOrientationCamera.position = this._position;
  78504. this._scene.activeCamera = this._deviceOrientationCamera;
  78505. if (this._canvas) {
  78506. this._scene.activeCamera.attachControl(this._canvas);
  78507. }
  78508. }
  78509. else if (this._existingCamera) {
  78510. this._existingCamera.position = this._position;
  78511. this._scene.activeCamera = this._existingCamera;
  78512. }
  78513. this.updateButtonVisibility();
  78514. if (this._interactionsEnabled) {
  78515. this._scene.unregisterBeforeRender(this.beforeRender);
  78516. }
  78517. };
  78518. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  78519. /**
  78520. * The position of the vr experience helper.
  78521. */
  78522. get: function () {
  78523. return this._position;
  78524. },
  78525. /**
  78526. * Sets the position of the vr experience helper.
  78527. */
  78528. set: function (value) {
  78529. this._position = value;
  78530. if (this._scene.activeCamera) {
  78531. this._scene.activeCamera.position = value;
  78532. }
  78533. },
  78534. enumerable: true,
  78535. configurable: true
  78536. });
  78537. /**
  78538. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  78539. */
  78540. VRExperienceHelper.prototype.enableInteractions = function () {
  78541. var _this = this;
  78542. if (!this._interactionsEnabled) {
  78543. this._interactionsRequested = true;
  78544. if (this._leftControllerReady && this._webVRCamera.leftController) {
  78545. this._enableInteractionOnController(this._webVRCamera.leftController);
  78546. }
  78547. if (this._rightControllerReady && this._webVRCamera.rightController) {
  78548. this._enableInteractionOnController(this._webVRCamera.rightController);
  78549. }
  78550. this._createGazeTracker();
  78551. this.raySelectionPredicate = function (mesh) {
  78552. return mesh.isVisible;
  78553. };
  78554. this.meshSelectionPredicate = function (mesh) {
  78555. return true;
  78556. };
  78557. this._raySelectionPredicate = function (mesh) {
  78558. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  78559. && mesh.name.indexOf("teleportationTarget") === -1
  78560. && mesh.name.indexOf("torusTeleportation") === -1
  78561. && mesh.name.indexOf("laserPointer") === -1)) {
  78562. return _this.raySelectionPredicate(mesh);
  78563. }
  78564. return false;
  78565. };
  78566. this._interactionsEnabled = true;
  78567. }
  78568. };
  78569. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  78570. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  78571. if (this._floorMeshesCollection[i].id === mesh.id) {
  78572. return true;
  78573. }
  78574. }
  78575. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  78576. return true;
  78577. }
  78578. return false;
  78579. };
  78580. /**
  78581. * Adds a floor mesh to be used for teleportation.
  78582. * @param floorMesh the mesh to be used for teleportation.
  78583. */
  78584. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  78585. if (!this._floorMeshesCollection) {
  78586. return;
  78587. }
  78588. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  78589. return;
  78590. }
  78591. this._floorMeshesCollection.push(floorMesh);
  78592. };
  78593. /**
  78594. * Removes a floor mesh from being used for teleportation.
  78595. * @param floorMesh the mesh to be removed.
  78596. */
  78597. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  78598. if (!this._floorMeshesCollection) {
  78599. return;
  78600. }
  78601. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  78602. if (meshIndex !== -1) {
  78603. this._floorMeshesCollection.splice(meshIndex, 1);
  78604. }
  78605. };
  78606. /**
  78607. * Enables interactions and teleportation using the VR controllers and gaze.
  78608. * @param vrTeleportationOptions options to modify teleportation behavior.
  78609. */
  78610. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  78611. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  78612. if (!this._teleportationInitialized) {
  78613. this._teleportationRequested = true;
  78614. this.enableInteractions();
  78615. if (vrTeleportationOptions.floorMeshName) {
  78616. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  78617. }
  78618. if (vrTeleportationOptions.floorMeshes) {
  78619. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  78620. }
  78621. if (this._leftControllerReady && this._webVRCamera.leftController) {
  78622. this._enableTeleportationOnController(this._webVRCamera.leftController);
  78623. }
  78624. if (this._rightControllerReady && this._webVRCamera.rightController) {
  78625. this._enableTeleportationOnController(this._webVRCamera.rightController);
  78626. }
  78627. // Creates an image processing post process for the vignette not relying
  78628. // on the main scene configuration for image processing to reduce setup and spaces
  78629. // (gamma/linear) conflicts.
  78630. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  78631. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  78632. imageProcessingConfiguration.vignetteEnabled = true;
  78633. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  78634. this._webVRCamera.detachPostProcess(this._postProcessMove);
  78635. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  78636. this._teleportationInitialized = true;
  78637. if (this._isDefaultTeleportationTarget) {
  78638. this._createTeleportationCircles();
  78639. }
  78640. }
  78641. };
  78642. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  78643. var _this = this;
  78644. var controllerMesh = webVRController.mesh;
  78645. if (controllerMesh) {
  78646. var makeNotPick = function (root) {
  78647. root.name += " laserPointer";
  78648. root.getChildMeshes().forEach(function (c) {
  78649. makeNotPick(c);
  78650. });
  78651. };
  78652. makeNotPick(controllerMesh);
  78653. var childMeshes = controllerMesh.getChildMeshes();
  78654. for (var i = 0; i < childMeshes.length; i++) {
  78655. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  78656. controllerMesh = childMeshes[i];
  78657. break;
  78658. }
  78659. }
  78660. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  78661. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  78662. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  78663. laserPointerMaterial.alpha = 0.6;
  78664. laserPointer.material = laserPointerMaterial;
  78665. laserPointer.rotation.x = Math.PI / 2;
  78666. laserPointer.parent = controllerMesh;
  78667. laserPointer.position.z = -0.5;
  78668. laserPointer.isVisible = false;
  78669. if (webVRController.hand === "left") {
  78670. this._leftLaserPointer = laserPointer;
  78671. this._interactionsEnabledOnLeftController = true;
  78672. if (!this._rightLaserPointer) {
  78673. this._leftLaserPointer.isVisible = true;
  78674. }
  78675. }
  78676. else {
  78677. this._rightLaserPointer = laserPointer;
  78678. this._interactionsEnabledOnRightController = true;
  78679. if (!this._leftLaserPointer) {
  78680. this._rightLaserPointer.isVisible = true;
  78681. }
  78682. }
  78683. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  78684. // Enabling / disabling laserPointer
  78685. if (_this._displayLaserPointer && stateObject.value === 1) {
  78686. laserPointer.isVisible = !laserPointer.isVisible;
  78687. // Laser pointer can only be active on left or right, not both at the same time
  78688. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  78689. _this._rightLaserPointer.isVisible = false;
  78690. }
  78691. else if (_this._leftLaserPointer) {
  78692. _this._leftLaserPointer.isVisible = false;
  78693. }
  78694. }
  78695. });
  78696. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  78697. if (!_this._pointerDownOnMeshAsked) {
  78698. if (stateObject.value > _this._padSensibilityUp) {
  78699. _this._selectionPointerDown();
  78700. }
  78701. }
  78702. else if (stateObject.value < _this._padSensibilityDown) {
  78703. _this._selectionPointerUp();
  78704. }
  78705. });
  78706. }
  78707. };
  78708. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  78709. if (webVRController === void 0) { webVRController = null; }
  78710. if (!this._teleportationRequestInitiated) {
  78711. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  78712. if (webVRController) {
  78713. // If laser pointer wasn't enabled yet
  78714. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  78715. this._leftLaserPointer.isVisible = true;
  78716. if (this._rightLaserPointer) {
  78717. this._rightLaserPointer.isVisible = false;
  78718. }
  78719. }
  78720. else if (this._displayLaserPointer && this._rightLaserPointer) {
  78721. this._rightLaserPointer.isVisible = true;
  78722. if (this._leftLaserPointer) {
  78723. this._leftLaserPointer.isVisible = false;
  78724. }
  78725. }
  78726. }
  78727. this._teleportationRequestInitiated = true;
  78728. }
  78729. }
  78730. else {
  78731. // Listening to the proper controller values changes to confirm teleportation
  78732. if (webVRController == null
  78733. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  78734. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  78735. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  78736. if (this._teleportationAllowed) {
  78737. this._teleportationAllowed = false;
  78738. this._teleportCamera();
  78739. }
  78740. this._teleportationRequestInitiated = false;
  78741. }
  78742. }
  78743. }
  78744. };
  78745. VRExperienceHelper.prototype._selectionPointerDown = function () {
  78746. this._pointerDownOnMeshAsked = true;
  78747. if (this._currentMeshSelected && this._currentHit) {
  78748. this._scene.simulatePointerDown(this._currentHit);
  78749. }
  78750. };
  78751. VRExperienceHelper.prototype._selectionPointerUp = function () {
  78752. if (this._currentMeshSelected && this._currentHit) {
  78753. this._scene.simulatePointerUp(this._currentHit);
  78754. }
  78755. this._pointerDownOnMeshAsked = false;
  78756. };
  78757. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  78758. // Only rotate when user is not currently selecting a teleportation location
  78759. if (this._teleportationRequestInitiated) {
  78760. return;
  78761. }
  78762. if (!this._rotationLeftAsked) {
  78763. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  78764. this._rotationLeftAsked = true;
  78765. if (this._rotationAllowed) {
  78766. this._rotateCamera(false);
  78767. }
  78768. }
  78769. }
  78770. else {
  78771. if (stateObject.x > -this._padSensibilityDown) {
  78772. this._rotationLeftAsked = false;
  78773. }
  78774. }
  78775. if (!this._rotationRightAsked) {
  78776. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  78777. this._rotationRightAsked = true;
  78778. if (this._rotationAllowed) {
  78779. this._rotateCamera(true);
  78780. }
  78781. }
  78782. }
  78783. else {
  78784. if (stateObject.x < this._padSensibilityDown) {
  78785. this._rotationRightAsked = false;
  78786. }
  78787. }
  78788. };
  78789. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  78790. // Only teleport backwards when user is not currently selecting a teleportation location
  78791. if (this._teleportationRequestInitiated) {
  78792. return;
  78793. }
  78794. // Teleport backwards
  78795. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  78796. if (!this._teleportationBackRequestInitiated) {
  78797. if (!this.currentVRCamera) {
  78798. return;
  78799. }
  78800. // Get rotation and position of the current camera
  78801. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  78802. var position = this.currentVRCamera.position;
  78803. // If the camera has device position, use that instead
  78804. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  78805. rotation = this.currentVRCamera.deviceRotationQuaternion;
  78806. position = this.currentVRCamera.devicePosition;
  78807. }
  78808. // Get matrix with only the y rotation of the device rotation
  78809. rotation.toEulerAnglesToRef(this._workingVector);
  78810. this._workingVector.z = 0;
  78811. this._workingVector.x = 0;
  78812. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  78813. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  78814. // Rotate backwards ray by device rotation to cast at the ground behind the user
  78815. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  78816. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  78817. var ray = new BABYLON.Ray(position, this._workingVector);
  78818. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  78819. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  78820. this._teleportCamera(hit.pickedPoint);
  78821. }
  78822. this._teleportationBackRequestInitiated = true;
  78823. }
  78824. }
  78825. else {
  78826. this._teleportationBackRequestInitiated = false;
  78827. }
  78828. };
  78829. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  78830. var _this = this;
  78831. var controllerMesh = webVRController.mesh;
  78832. if (controllerMesh) {
  78833. if (webVRController.hand === "left") {
  78834. if (!this._interactionsEnabledOnLeftController) {
  78835. this._enableInteractionOnController(webVRController);
  78836. }
  78837. this._teleportationEnabledOnLeftController = true;
  78838. }
  78839. else {
  78840. if (!this._interactionsEnabledOnRightController) {
  78841. this._enableInteractionOnController(webVRController);
  78842. }
  78843. this._teleportationEnabledOnRightController = true;
  78844. }
  78845. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  78846. this._dpadPressed = false;
  78847. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  78848. _this._dpadPressed = stateObject.pressed;
  78849. if (!_this._dpadPressed) {
  78850. _this._rotationLeftAsked = false;
  78851. _this._rotationRightAsked = false;
  78852. _this._teleportationBackRequestInitiated = false;
  78853. }
  78854. });
  78855. }
  78856. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  78857. if (_this.teleportationEnabled) {
  78858. _this._checkTeleportBackwards(stateObject);
  78859. _this._checkTeleportWithRay(stateObject, webVRController);
  78860. }
  78861. _this._checkRotate(stateObject);
  78862. });
  78863. }
  78864. };
  78865. // Gaze support used to point to teleport or to interact with an object
  78866. VRExperienceHelper.prototype._createGazeTracker = function () {
  78867. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  78868. this._gazeTracker.bakeCurrentTransformIntoVertices();
  78869. this._gazeTracker.isPickable = false;
  78870. this._gazeTracker.isVisible = false;
  78871. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  78872. targetMat.specularColor = BABYLON.Color3.Black();
  78873. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  78874. targetMat.backFaceCulling = false;
  78875. this._gazeTracker.material = targetMat;
  78876. };
  78877. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  78878. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  78879. this._teleportationTarget.isPickable = false;
  78880. var length = 512;
  78881. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  78882. dynamicTexture.hasAlpha = true;
  78883. var context = dynamicTexture.getContext();
  78884. var centerX = length / 2;
  78885. var centerY = length / 2;
  78886. var radius = 200;
  78887. context.beginPath();
  78888. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  78889. context.fillStyle = this._teleportationFillColor;
  78890. context.fill();
  78891. context.lineWidth = 10;
  78892. context.strokeStyle = this._teleportationBorderColor;
  78893. context.stroke();
  78894. context.closePath();
  78895. dynamicTexture.update();
  78896. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  78897. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  78898. this._teleportationTarget.material = teleportationCircleMaterial;
  78899. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  78900. torus.isPickable = false;
  78901. torus.parent = this._teleportationTarget;
  78902. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  78903. var keys = [];
  78904. keys.push({
  78905. frame: 0,
  78906. value: 0
  78907. });
  78908. keys.push({
  78909. frame: 30,
  78910. value: 0.4
  78911. });
  78912. keys.push({
  78913. frame: 60,
  78914. value: 0
  78915. });
  78916. animationInnerCircle.setKeys(keys);
  78917. var easingFunction = new BABYLON.SineEase();
  78918. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  78919. animationInnerCircle.setEasingFunction(easingFunction);
  78920. torus.animations = [];
  78921. torus.animations.push(animationInnerCircle);
  78922. this._scene.beginAnimation(torus, 0, 60, true);
  78923. this._hideTeleportationTarget();
  78924. };
  78925. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  78926. if (this._teleportationInitialized) {
  78927. this._teleportationTarget.isVisible = true;
  78928. if (this._isDefaultTeleportationTarget) {
  78929. this._teleportationTarget.getChildren()[0].isVisible = true;
  78930. }
  78931. }
  78932. };
  78933. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  78934. if (this._teleportationInitialized) {
  78935. this._teleportationTarget.isVisible = false;
  78936. if (this._isDefaultTeleportationTarget) {
  78937. this._teleportationTarget.getChildren()[0].isVisible = false;
  78938. }
  78939. }
  78940. };
  78941. VRExperienceHelper.prototype._rotateCamera = function (right) {
  78942. var _this = this;
  78943. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  78944. return;
  78945. }
  78946. if (right) {
  78947. this._rotationAngle++;
  78948. }
  78949. else {
  78950. this._rotationAngle--;
  78951. }
  78952. this.currentVRCamera.animations = [];
  78953. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  78954. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  78955. var animationRotationKeys = [];
  78956. animationRotationKeys.push({
  78957. frame: 0,
  78958. value: this.currentVRCamera.rotationQuaternion
  78959. });
  78960. animationRotationKeys.push({
  78961. frame: 6,
  78962. value: target
  78963. });
  78964. animationRotation.setKeys(animationRotationKeys);
  78965. animationRotation.setEasingFunction(this._circleEase);
  78966. this.currentVRCamera.animations.push(animationRotation);
  78967. this._postProcessMove.animations = [];
  78968. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  78969. var vignetteWeightKeys = [];
  78970. vignetteWeightKeys.push({
  78971. frame: 0,
  78972. value: 0
  78973. });
  78974. vignetteWeightKeys.push({
  78975. frame: 3,
  78976. value: 4
  78977. });
  78978. vignetteWeightKeys.push({
  78979. frame: 6,
  78980. value: 0
  78981. });
  78982. animationPP.setKeys(vignetteWeightKeys);
  78983. animationPP.setEasingFunction(this._circleEase);
  78984. this._postProcessMove.animations.push(animationPP);
  78985. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  78986. var vignetteStretchKeys = [];
  78987. vignetteStretchKeys.push({
  78988. frame: 0,
  78989. value: 0
  78990. });
  78991. vignetteStretchKeys.push({
  78992. frame: 3,
  78993. value: 10
  78994. });
  78995. vignetteStretchKeys.push({
  78996. frame: 6,
  78997. value: 0
  78998. });
  78999. animationPP2.setKeys(vignetteStretchKeys);
  79000. animationPP2.setEasingFunction(this._circleEase);
  79001. this._postProcessMove.animations.push(animationPP2);
  79002. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  79003. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  79004. this._webVRCamera.attachPostProcess(this._postProcessMove);
  79005. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  79006. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  79007. });
  79008. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  79009. };
  79010. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  79011. if (hit.pickedPoint) {
  79012. this._teleportationAllowed = true;
  79013. if (this._teleportationRequestInitiated) {
  79014. this._displayTeleportationTarget();
  79015. }
  79016. else {
  79017. this._hideTeleportationTarget();
  79018. }
  79019. this._haloCenter.copyFrom(hit.pickedPoint);
  79020. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  79021. var pickNormal = hit.getNormal(true, false);
  79022. if (pickNormal) {
  79023. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  79024. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  79025. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  79026. }
  79027. this._teleportationTarget.position.y += 0.1;
  79028. }
  79029. };
  79030. VRExperienceHelper.prototype._teleportCamera = function (location) {
  79031. var _this = this;
  79032. if (location === void 0) { location = null; }
  79033. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79034. return;
  79035. }
  79036. if (!location) {
  79037. location = this._haloCenter;
  79038. }
  79039. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  79040. // offset of the headset from the anchor.
  79041. if (this.webVRCamera.leftCamera) {
  79042. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  79043. this._workingVector.subtractInPlace(this.webVRCamera.position);
  79044. location.subtractToRef(this._workingVector, this._workingVector);
  79045. }
  79046. else {
  79047. this._workingVector.copyFrom(location);
  79048. }
  79049. // Add height to account for user's height offset
  79050. if (this.isInVRMode) {
  79051. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  79052. }
  79053. else {
  79054. this._workingVector.y += this._defaultHeight;
  79055. }
  79056. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  79057. // Create animation from the camera's position to the new location
  79058. this.currentVRCamera.animations = [];
  79059. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79060. var animationCameraTeleportationKeys = [{
  79061. frame: 0,
  79062. value: this.currentVRCamera.position
  79063. },
  79064. {
  79065. frame: 11,
  79066. value: this._workingVector
  79067. }
  79068. ];
  79069. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  79070. animationCameraTeleportation.setEasingFunction(this._circleEase);
  79071. this.currentVRCamera.animations.push(animationCameraTeleportation);
  79072. this._postProcessMove.animations = [];
  79073. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79074. var vignetteWeightKeys = [];
  79075. vignetteWeightKeys.push({
  79076. frame: 0,
  79077. value: 0
  79078. });
  79079. vignetteWeightKeys.push({
  79080. frame: 5,
  79081. value: 8
  79082. });
  79083. vignetteWeightKeys.push({
  79084. frame: 11,
  79085. value: 0
  79086. });
  79087. animationPP.setKeys(vignetteWeightKeys);
  79088. this._postProcessMove.animations.push(animationPP);
  79089. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79090. var vignetteStretchKeys = [];
  79091. vignetteStretchKeys.push({
  79092. frame: 0,
  79093. value: 0
  79094. });
  79095. vignetteStretchKeys.push({
  79096. frame: 5,
  79097. value: 10
  79098. });
  79099. vignetteStretchKeys.push({
  79100. frame: 11,
  79101. value: 0
  79102. });
  79103. animationPP2.setKeys(vignetteStretchKeys);
  79104. this._postProcessMove.animations.push(animationPP2);
  79105. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  79106. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  79107. this._webVRCamera.attachPostProcess(this._postProcessMove);
  79108. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  79109. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  79110. });
  79111. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  79112. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  79113. });
  79114. };
  79115. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  79116. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79117. return;
  79118. }
  79119. var ray;
  79120. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  79121. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  79122. }
  79123. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  79124. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  79125. }
  79126. else {
  79127. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  79128. }
  79129. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  79130. // Moving the gazeTracker on the mesh face targetted
  79131. if (hit && hit.pickedPoint) {
  79132. if (this._displayGaze) {
  79133. var multiplier = 1;
  79134. this._gazeTracker.isVisible = true;
  79135. if (this._isActionableMesh) {
  79136. multiplier = 3;
  79137. }
  79138. this._gazeTracker.scaling.x = hit.distance * multiplier;
  79139. this._gazeTracker.scaling.y = hit.distance * multiplier;
  79140. this._gazeTracker.scaling.z = hit.distance * multiplier;
  79141. var pickNormal = hit.getNormal();
  79142. // To avoid z-fighting
  79143. var deltaFighting = 0.002;
  79144. if (pickNormal) {
  79145. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  79146. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  79147. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  79148. }
  79149. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  79150. if (this._gazeTracker.position.x < 0) {
  79151. this._gazeTracker.position.x += deltaFighting;
  79152. }
  79153. else {
  79154. this._gazeTracker.position.x -= deltaFighting;
  79155. }
  79156. if (this._gazeTracker.position.y < 0) {
  79157. this._gazeTracker.position.y += deltaFighting;
  79158. }
  79159. else {
  79160. this._gazeTracker.position.y -= deltaFighting;
  79161. }
  79162. if (this._gazeTracker.position.z < 0) {
  79163. this._gazeTracker.position.z += deltaFighting;
  79164. }
  79165. else {
  79166. this._gazeTracker.position.z -= deltaFighting;
  79167. }
  79168. }
  79169. // Changing the size of the laser pointer based on the distance from the targetted point
  79170. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  79171. this._rightLaserPointer.scaling.y = hit.distance;
  79172. this._rightLaserPointer.position.z = -hit.distance / 2;
  79173. }
  79174. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  79175. this._leftLaserPointer.scaling.y = hit.distance;
  79176. this._leftLaserPointer.position.z = -hit.distance / 2;
  79177. }
  79178. }
  79179. else {
  79180. this._gazeTracker.isVisible = false;
  79181. }
  79182. if (hit && hit.pickedMesh) {
  79183. this._currentHit = hit;
  79184. if (this._pointerDownOnMeshAsked) {
  79185. this._scene.simulatePointerMove(this._currentHit);
  79186. }
  79187. // The object selected is the floor, we're in a teleportation scenario
  79188. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  79189. // Moving the teleportation area to this targetted point
  79190. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  79191. if (this._currentMeshSelected && !this._isTeleportationFloor(this._currentMeshSelected)) {
  79192. this._notifySelectedMeshUnselected();
  79193. }
  79194. this._currentMeshSelected = null;
  79195. this._moveTeleportationSelectorTo(hit);
  79196. return;
  79197. }
  79198. // If not, we're in a selection scenario
  79199. this._hideTeleportationTarget();
  79200. this._teleportationAllowed = false;
  79201. if (hit.pickedMesh !== this._currentMeshSelected) {
  79202. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  79203. this.onNewMeshPicked.notifyObservers(hit);
  79204. this._currentMeshSelected = hit.pickedMesh;
  79205. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  79206. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  79207. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  79208. this._isActionableMesh = true;
  79209. }
  79210. else {
  79211. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79212. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79213. this._isActionableMesh = false;
  79214. }
  79215. try {
  79216. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  79217. }
  79218. catch (err) {
  79219. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  79220. }
  79221. }
  79222. else {
  79223. this._notifySelectedMeshUnselected();
  79224. this._currentMeshSelected = null;
  79225. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79226. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79227. }
  79228. }
  79229. }
  79230. else {
  79231. this._currentHit = null;
  79232. this._notifySelectedMeshUnselected();
  79233. this._currentMeshSelected = null;
  79234. this._teleportationAllowed = false;
  79235. this._hideTeleportationTarget();
  79236. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79237. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79238. }
  79239. };
  79240. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function () {
  79241. if (this._currentMeshSelected) {
  79242. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  79243. }
  79244. };
  79245. /**
  79246. * Sets the color of the laser ray from the vr controllers.
  79247. * @param color new color for the ray.
  79248. */
  79249. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  79250. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  79251. this._leftLaserPointer.material.emissiveColor = color;
  79252. }
  79253. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  79254. this._rightLaserPointer.material.emissiveColor = color;
  79255. }
  79256. };
  79257. /**
  79258. * Sets the color of the ray from the vr headsets gaze.
  79259. * @param color new color for the ray.
  79260. */
  79261. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  79262. if (this._gazeTracker.material) {
  79263. this._gazeTracker.material.emissiveColor = color;
  79264. }
  79265. };
  79266. /**
  79267. * Exits VR and disposes of the vr experience helper
  79268. */
  79269. VRExperienceHelper.prototype.dispose = function () {
  79270. if (this.isInVRMode) {
  79271. this.exitVR();
  79272. }
  79273. if (this._passProcessMove) {
  79274. this._passProcessMove.dispose();
  79275. }
  79276. if (this._postProcessMove) {
  79277. this._postProcessMove.dispose();
  79278. }
  79279. if (this._webVRCamera) {
  79280. this._webVRCamera.dispose();
  79281. }
  79282. if (this._vrDeviceOrientationCamera) {
  79283. this._vrDeviceOrientationCamera.dispose();
  79284. }
  79285. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  79286. document.body.removeChild(this._btnVR);
  79287. }
  79288. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  79289. this._deviceOrientationCamera.dispose();
  79290. }
  79291. if (this._gazeTracker) {
  79292. this._gazeTracker.dispose();
  79293. }
  79294. if (this._teleportationTarget) {
  79295. this._teleportationTarget.dispose();
  79296. }
  79297. this._floorMeshesCollection = [];
  79298. document.removeEventListener("keydown", this._onKeyDown);
  79299. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  79300. window.removeEventListener("resize", this._onResize);
  79301. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  79302. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  79303. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  79304. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  79305. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  79306. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  79307. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  79308. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  79309. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  79310. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  79311. this._scene.unregisterBeforeRender(this.beforeRender);
  79312. };
  79313. /**
  79314. * Gets the name of the VRExperienceHelper class
  79315. * @returns "VRExperienceHelper"
  79316. */
  79317. VRExperienceHelper.prototype.getClassName = function () {
  79318. return "VRExperienceHelper";
  79319. };
  79320. return VRExperienceHelper;
  79321. }());
  79322. BABYLON.VRExperienceHelper = VRExperienceHelper;
  79323. })(BABYLON || (BABYLON = {}));
  79324. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  79325. // Mainly based on these 2 articles :
  79326. // 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
  79327. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  79328. var BABYLON;
  79329. (function (BABYLON) {
  79330. var JoystickAxis;
  79331. (function (JoystickAxis) {
  79332. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  79333. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  79334. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  79335. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  79336. var VirtualJoystick = /** @class */ (function () {
  79337. function VirtualJoystick(leftJoystick) {
  79338. var _this = this;
  79339. if (leftJoystick) {
  79340. this._leftJoystick = true;
  79341. }
  79342. else {
  79343. this._leftJoystick = false;
  79344. }
  79345. VirtualJoystick._globalJoystickIndex++;
  79346. // By default left & right arrow keys are moving the X
  79347. // and up & down keys are moving the Y
  79348. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  79349. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  79350. this.reverseLeftRight = false;
  79351. this.reverseUpDown = false;
  79352. // collections of pointers
  79353. this._touches = new BABYLON.StringDictionary();
  79354. this.deltaPosition = BABYLON.Vector3.Zero();
  79355. this._joystickSensibility = 25;
  79356. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  79357. this._onResize = function (evt) {
  79358. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  79359. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  79360. if (VirtualJoystick.vjCanvas) {
  79361. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  79362. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  79363. }
  79364. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  79365. };
  79366. // injecting a canvas element on top of the canvas 3D game
  79367. if (!VirtualJoystick.vjCanvas) {
  79368. window.addEventListener("resize", this._onResize, false);
  79369. VirtualJoystick.vjCanvas = document.createElement("canvas");
  79370. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  79371. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  79372. VirtualJoystick.vjCanvas.width = window.innerWidth;
  79373. VirtualJoystick.vjCanvas.height = window.innerHeight;
  79374. VirtualJoystick.vjCanvas.style.width = "100%";
  79375. VirtualJoystick.vjCanvas.style.height = "100%";
  79376. VirtualJoystick.vjCanvas.style.position = "absolute";
  79377. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  79378. VirtualJoystick.vjCanvas.style.top = "0px";
  79379. VirtualJoystick.vjCanvas.style.left = "0px";
  79380. VirtualJoystick.vjCanvas.style.zIndex = "5";
  79381. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  79382. // Support for jQuery PEP polyfill
  79383. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  79384. var context = VirtualJoystick.vjCanvas.getContext('2d');
  79385. if (!context) {
  79386. throw new Error("Unable to create canvas for virtual joystick");
  79387. }
  79388. VirtualJoystick.vjCanvasContext = context;
  79389. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  79390. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  79391. document.body.appendChild(VirtualJoystick.vjCanvas);
  79392. }
  79393. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  79394. this.pressed = false;
  79395. // default joystick color
  79396. this._joystickColor = "cyan";
  79397. this._joystickPointerID = -1;
  79398. // current joystick position
  79399. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  79400. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  79401. // origin joystick position
  79402. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  79403. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  79404. this._onPointerDownHandlerRef = function (evt) {
  79405. _this._onPointerDown(evt);
  79406. };
  79407. this._onPointerMoveHandlerRef = function (evt) {
  79408. _this._onPointerMove(evt);
  79409. };
  79410. this._onPointerUpHandlerRef = function (evt) {
  79411. _this._onPointerUp(evt);
  79412. };
  79413. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  79414. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  79415. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  79416. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  79417. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  79418. evt.preventDefault(); // Disables system menu
  79419. }, false);
  79420. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  79421. }
  79422. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  79423. this._joystickSensibility = newJoystickSensibility;
  79424. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  79425. };
  79426. VirtualJoystick.prototype._onPointerDown = function (e) {
  79427. var positionOnScreenCondition;
  79428. e.preventDefault();
  79429. if (this._leftJoystick === true) {
  79430. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  79431. }
  79432. else {
  79433. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  79434. }
  79435. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  79436. // First contact will be dedicated to the virtual joystick
  79437. this._joystickPointerID = e.pointerId;
  79438. this._joystickPointerStartPos.x = e.clientX;
  79439. this._joystickPointerStartPos.y = e.clientY;
  79440. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  79441. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  79442. this._deltaJoystickVector.x = 0;
  79443. this._deltaJoystickVector.y = 0;
  79444. this.pressed = true;
  79445. this._touches.add(e.pointerId.toString(), e);
  79446. }
  79447. else {
  79448. // You can only trigger the action buttons with a joystick declared
  79449. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  79450. this._action();
  79451. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  79452. }
  79453. }
  79454. };
  79455. VirtualJoystick.prototype._onPointerMove = function (e) {
  79456. // If the current pointer is the one associated to the joystick (first touch contact)
  79457. if (this._joystickPointerID == e.pointerId) {
  79458. this._joystickPointerPos.x = e.clientX;
  79459. this._joystickPointerPos.y = e.clientY;
  79460. this._deltaJoystickVector = this._joystickPointerPos.clone();
  79461. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  79462. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  79463. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  79464. switch (this._axisTargetedByLeftAndRight) {
  79465. case JoystickAxis.X:
  79466. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  79467. break;
  79468. case JoystickAxis.Y:
  79469. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  79470. break;
  79471. case JoystickAxis.Z:
  79472. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  79473. break;
  79474. }
  79475. var directionUpDown = this.reverseUpDown ? 1 : -1;
  79476. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  79477. switch (this._axisTargetedByUpAndDown) {
  79478. case JoystickAxis.X:
  79479. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  79480. break;
  79481. case JoystickAxis.Y:
  79482. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  79483. break;
  79484. case JoystickAxis.Z:
  79485. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  79486. break;
  79487. }
  79488. }
  79489. else {
  79490. var data = this._touches.get(e.pointerId.toString());
  79491. if (data) {
  79492. data.x = e.clientX;
  79493. data.y = e.clientY;
  79494. }
  79495. }
  79496. };
  79497. VirtualJoystick.prototype._onPointerUp = function (e) {
  79498. if (this._joystickPointerID == e.pointerId) {
  79499. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  79500. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  79501. this._joystickPointerID = -1;
  79502. this.pressed = false;
  79503. }
  79504. else {
  79505. var touch = this._touches.get(e.pointerId.toString());
  79506. if (touch) {
  79507. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  79508. }
  79509. }
  79510. this._deltaJoystickVector.x = 0;
  79511. this._deltaJoystickVector.y = 0;
  79512. this._touches.remove(e.pointerId.toString());
  79513. };
  79514. /**
  79515. * Change the color of the virtual joystick
  79516. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  79517. */
  79518. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  79519. this._joystickColor = newColor;
  79520. };
  79521. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  79522. this._action = action;
  79523. };
  79524. // Define which axis you'd like to control for left & right
  79525. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  79526. switch (axis) {
  79527. case JoystickAxis.X:
  79528. case JoystickAxis.Y:
  79529. case JoystickAxis.Z:
  79530. this._axisTargetedByLeftAndRight = axis;
  79531. break;
  79532. default:
  79533. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  79534. break;
  79535. }
  79536. };
  79537. // Define which axis you'd like to control for up & down
  79538. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  79539. switch (axis) {
  79540. case JoystickAxis.X:
  79541. case JoystickAxis.Y:
  79542. case JoystickAxis.Z:
  79543. this._axisTargetedByUpAndDown = axis;
  79544. break;
  79545. default:
  79546. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  79547. break;
  79548. }
  79549. };
  79550. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  79551. var _this = this;
  79552. if (this.pressed) {
  79553. this._touches.forEach(function (key, touch) {
  79554. if (touch.pointerId === _this._joystickPointerID) {
  79555. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  79556. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  79557. VirtualJoystick.vjCanvasContext.beginPath();
  79558. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  79559. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  79560. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  79561. VirtualJoystick.vjCanvasContext.stroke();
  79562. VirtualJoystick.vjCanvasContext.closePath();
  79563. VirtualJoystick.vjCanvasContext.beginPath();
  79564. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  79565. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  79566. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  79567. VirtualJoystick.vjCanvasContext.stroke();
  79568. VirtualJoystick.vjCanvasContext.closePath();
  79569. VirtualJoystick.vjCanvasContext.beginPath();
  79570. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  79571. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  79572. VirtualJoystick.vjCanvasContext.stroke();
  79573. VirtualJoystick.vjCanvasContext.closePath();
  79574. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  79575. }
  79576. else {
  79577. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  79578. VirtualJoystick.vjCanvasContext.beginPath();
  79579. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  79580. VirtualJoystick.vjCanvasContext.beginPath();
  79581. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  79582. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  79583. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  79584. VirtualJoystick.vjCanvasContext.stroke();
  79585. VirtualJoystick.vjCanvasContext.closePath();
  79586. touch.prevX = touch.x;
  79587. touch.prevY = touch.y;
  79588. }
  79589. ;
  79590. });
  79591. }
  79592. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  79593. };
  79594. VirtualJoystick.prototype.releaseCanvas = function () {
  79595. if (VirtualJoystick.vjCanvas) {
  79596. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  79597. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  79598. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  79599. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  79600. window.removeEventListener("resize", this._onResize);
  79601. document.body.removeChild(VirtualJoystick.vjCanvas);
  79602. VirtualJoystick.vjCanvas = null;
  79603. }
  79604. };
  79605. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  79606. VirtualJoystick._globalJoystickIndex = 0;
  79607. return VirtualJoystick;
  79608. }());
  79609. BABYLON.VirtualJoystick = VirtualJoystick;
  79610. })(BABYLON || (BABYLON = {}));
  79611. //# sourceMappingURL=babylon.virtualJoystick.js.map
  79612. var BABYLON;
  79613. (function (BABYLON) {
  79614. // We're mainly based on the logic defined into the FreeCamera code
  79615. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  79616. __extends(VirtualJoysticksCamera, _super);
  79617. function VirtualJoysticksCamera(name, position, scene) {
  79618. var _this = _super.call(this, name, position, scene) || this;
  79619. _this.inputs.addVirtualJoystick();
  79620. return _this;
  79621. }
  79622. VirtualJoysticksCamera.prototype.getClassName = function () {
  79623. return "VirtualJoysticksCamera";
  79624. };
  79625. return VirtualJoysticksCamera;
  79626. }(BABYLON.FreeCamera));
  79627. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  79628. })(BABYLON || (BABYLON = {}));
  79629. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  79630. var BABYLON;
  79631. (function (BABYLON) {
  79632. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  79633. function FreeCameraVirtualJoystickInput() {
  79634. }
  79635. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  79636. return this._leftjoystick;
  79637. };
  79638. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  79639. return this._rightjoystick;
  79640. };
  79641. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  79642. if (this._leftjoystick) {
  79643. var camera = this.camera;
  79644. var speed = camera._computeLocalCameraSpeed() * 50;
  79645. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  79646. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  79647. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  79648. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  79649. if (!this._leftjoystick.pressed) {
  79650. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  79651. }
  79652. if (!this._rightjoystick.pressed) {
  79653. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  79654. }
  79655. }
  79656. };
  79657. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  79658. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  79659. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  79660. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  79661. this._leftjoystick.setJoystickSensibility(0.15);
  79662. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  79663. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  79664. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  79665. this._rightjoystick.reverseUpDown = true;
  79666. this._rightjoystick.setJoystickSensibility(0.05);
  79667. this._rightjoystick.setJoystickColor("yellow");
  79668. };
  79669. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  79670. this._leftjoystick.releaseCanvas();
  79671. this._rightjoystick.releaseCanvas();
  79672. };
  79673. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  79674. return "FreeCameraVirtualJoystickInput";
  79675. };
  79676. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  79677. return "virtualJoystick";
  79678. };
  79679. return FreeCameraVirtualJoystickInput;
  79680. }());
  79681. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  79682. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  79683. })(BABYLON || (BABYLON = {}));
  79684. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  79685. var BABYLON;
  79686. (function (BABYLON) {
  79687. var SimplificationSettings = /** @class */ (function () {
  79688. function SimplificationSettings(quality, distance, optimizeMesh) {
  79689. this.quality = quality;
  79690. this.distance = distance;
  79691. this.optimizeMesh = optimizeMesh;
  79692. }
  79693. return SimplificationSettings;
  79694. }());
  79695. BABYLON.SimplificationSettings = SimplificationSettings;
  79696. var SimplificationQueue = /** @class */ (function () {
  79697. function SimplificationQueue() {
  79698. this.running = false;
  79699. this._simplificationArray = [];
  79700. }
  79701. SimplificationQueue.prototype.addTask = function (task) {
  79702. this._simplificationArray.push(task);
  79703. };
  79704. SimplificationQueue.prototype.executeNext = function () {
  79705. var task = this._simplificationArray.pop();
  79706. if (task) {
  79707. this.running = true;
  79708. this.runSimplification(task);
  79709. }
  79710. else {
  79711. this.running = false;
  79712. }
  79713. };
  79714. SimplificationQueue.prototype.runSimplification = function (task) {
  79715. var _this = this;
  79716. if (task.parallelProcessing) {
  79717. //parallel simplifier
  79718. task.settings.forEach(function (setting) {
  79719. var simplifier = _this.getSimplifier(task);
  79720. simplifier.simplify(setting, function (newMesh) {
  79721. task.mesh.addLODLevel(setting.distance, newMesh);
  79722. newMesh.isVisible = true;
  79723. //check if it is the last
  79724. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  79725. //all done, run the success callback.
  79726. task.successCallback();
  79727. }
  79728. _this.executeNext();
  79729. });
  79730. });
  79731. }
  79732. else {
  79733. //single simplifier.
  79734. var simplifier = this.getSimplifier(task);
  79735. var runDecimation = function (setting, callback) {
  79736. simplifier.simplify(setting, function (newMesh) {
  79737. task.mesh.addLODLevel(setting.distance, newMesh);
  79738. newMesh.isVisible = true;
  79739. //run the next quality level
  79740. callback();
  79741. });
  79742. };
  79743. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  79744. runDecimation(task.settings[loop.index], function () {
  79745. loop.executeNext();
  79746. });
  79747. }, function () {
  79748. //execution ended, run the success callback.
  79749. if (task.successCallback) {
  79750. task.successCallback();
  79751. }
  79752. _this.executeNext();
  79753. });
  79754. }
  79755. };
  79756. SimplificationQueue.prototype.getSimplifier = function (task) {
  79757. switch (task.simplificationType) {
  79758. case SimplificationType.QUADRATIC:
  79759. default:
  79760. return new QuadraticErrorSimplification(task.mesh);
  79761. }
  79762. };
  79763. return SimplificationQueue;
  79764. }());
  79765. BABYLON.SimplificationQueue = SimplificationQueue;
  79766. /**
  79767. * The implemented types of simplification.
  79768. * At the moment only Quadratic Error Decimation is implemented.
  79769. */
  79770. var SimplificationType;
  79771. (function (SimplificationType) {
  79772. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  79773. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  79774. var DecimationTriangle = /** @class */ (function () {
  79775. function DecimationTriangle(vertices) {
  79776. this.vertices = vertices;
  79777. this.error = new Array(4);
  79778. this.deleted = false;
  79779. this.isDirty = false;
  79780. this.deletePending = false;
  79781. this.borderFactor = 0;
  79782. }
  79783. return DecimationTriangle;
  79784. }());
  79785. BABYLON.DecimationTriangle = DecimationTriangle;
  79786. var DecimationVertex = /** @class */ (function () {
  79787. function DecimationVertex(position, id) {
  79788. this.position = position;
  79789. this.id = id;
  79790. this.isBorder = true;
  79791. this.q = new QuadraticMatrix();
  79792. this.triangleCount = 0;
  79793. this.triangleStart = 0;
  79794. this.originalOffsets = [];
  79795. }
  79796. DecimationVertex.prototype.updatePosition = function (newPosition) {
  79797. this.position.copyFrom(newPosition);
  79798. };
  79799. return DecimationVertex;
  79800. }());
  79801. BABYLON.DecimationVertex = DecimationVertex;
  79802. var QuadraticMatrix = /** @class */ (function () {
  79803. function QuadraticMatrix(data) {
  79804. this.data = new Array(10);
  79805. for (var i = 0; i < 10; ++i) {
  79806. if (data && data[i]) {
  79807. this.data[i] = data[i];
  79808. }
  79809. else {
  79810. this.data[i] = 0;
  79811. }
  79812. }
  79813. }
  79814. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  79815. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  79816. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  79817. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  79818. return det;
  79819. };
  79820. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  79821. for (var i = 0; i < 10; ++i) {
  79822. this.data[i] += matrix.data[i];
  79823. }
  79824. };
  79825. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  79826. for (var i = 0; i < 10; ++i) {
  79827. this.data[i] += data[i];
  79828. }
  79829. };
  79830. QuadraticMatrix.prototype.add = function (matrix) {
  79831. var m = new QuadraticMatrix();
  79832. for (var i = 0; i < 10; ++i) {
  79833. m.data[i] = this.data[i] + matrix.data[i];
  79834. }
  79835. return m;
  79836. };
  79837. QuadraticMatrix.FromData = function (a, b, c, d) {
  79838. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  79839. };
  79840. //returning an array to avoid garbage collection
  79841. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  79842. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  79843. };
  79844. return QuadraticMatrix;
  79845. }());
  79846. BABYLON.QuadraticMatrix = QuadraticMatrix;
  79847. var Reference = /** @class */ (function () {
  79848. function Reference(vertexId, triangleId) {
  79849. this.vertexId = vertexId;
  79850. this.triangleId = triangleId;
  79851. }
  79852. return Reference;
  79853. }());
  79854. BABYLON.Reference = Reference;
  79855. /**
  79856. * An implementation of the Quadratic Error simplification algorithm.
  79857. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  79858. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  79859. * @author RaananW
  79860. */
  79861. var QuadraticErrorSimplification = /** @class */ (function () {
  79862. function QuadraticErrorSimplification(_mesh) {
  79863. this._mesh = _mesh;
  79864. this.syncIterations = 5000;
  79865. this.aggressiveness = 7;
  79866. this.decimationIterations = 100;
  79867. this.boundingBoxEpsilon = BABYLON.Epsilon;
  79868. }
  79869. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  79870. var _this = this;
  79871. this.initDecimatedMesh();
  79872. //iterating through the submeshes array, one after the other.
  79873. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  79874. _this.initWithMesh(loop.index, function () {
  79875. _this.runDecimation(settings, loop.index, function () {
  79876. loop.executeNext();
  79877. });
  79878. }, settings.optimizeMesh);
  79879. }, function () {
  79880. setTimeout(function () {
  79881. successCallback(_this._reconstructedMesh);
  79882. }, 0);
  79883. });
  79884. };
  79885. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  79886. var _this = this;
  79887. var targetCount = ~~(this.triangles.length * settings.quality);
  79888. var deletedTriangles = 0;
  79889. var triangleCount = this.triangles.length;
  79890. var iterationFunction = function (iteration, callback) {
  79891. setTimeout(function () {
  79892. if (iteration % 5 === 0) {
  79893. _this.updateMesh(iteration === 0);
  79894. }
  79895. for (var i = 0; i < _this.triangles.length; ++i) {
  79896. _this.triangles[i].isDirty = false;
  79897. }
  79898. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  79899. var trianglesIterator = function (i) {
  79900. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  79901. var t = _this.triangles[tIdx];
  79902. if (!t)
  79903. return;
  79904. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  79905. return;
  79906. }
  79907. for (var j = 0; j < 3; ++j) {
  79908. if (t.error[j] < threshold) {
  79909. var deleted0 = [];
  79910. var deleted1 = [];
  79911. var v0 = t.vertices[j];
  79912. var v1 = t.vertices[(j + 1) % 3];
  79913. if (v0.isBorder || v1.isBorder)
  79914. continue;
  79915. var p = BABYLON.Vector3.Zero();
  79916. var n = BABYLON.Vector3.Zero();
  79917. var uv = BABYLON.Vector2.Zero();
  79918. var color = new BABYLON.Color4(0, 0, 0, 1);
  79919. _this.calculateError(v0, v1, p, n, uv, color);
  79920. var delTr = new Array();
  79921. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  79922. continue;
  79923. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  79924. continue;
  79925. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  79926. continue;
  79927. var uniqueArray = new Array();
  79928. delTr.forEach(function (deletedT) {
  79929. if (uniqueArray.indexOf(deletedT) === -1) {
  79930. deletedT.deletePending = true;
  79931. uniqueArray.push(deletedT);
  79932. }
  79933. });
  79934. if (uniqueArray.length % 2 !== 0) {
  79935. continue;
  79936. }
  79937. v0.q = v1.q.add(v0.q);
  79938. v0.updatePosition(p);
  79939. var tStart = _this.references.length;
  79940. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  79941. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  79942. var tCount = _this.references.length - tStart;
  79943. if (tCount <= v0.triangleCount) {
  79944. if (tCount) {
  79945. for (var c = 0; c < tCount; c++) {
  79946. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  79947. }
  79948. }
  79949. }
  79950. else {
  79951. v0.triangleStart = tStart;
  79952. }
  79953. v0.triangleCount = tCount;
  79954. break;
  79955. }
  79956. }
  79957. };
  79958. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  79959. }, 0);
  79960. };
  79961. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  79962. if (triangleCount - deletedTriangles <= targetCount)
  79963. loop.breakLoop();
  79964. else {
  79965. iterationFunction(loop.index, function () {
  79966. loop.executeNext();
  79967. });
  79968. }
  79969. }, function () {
  79970. setTimeout(function () {
  79971. //reconstruct this part of the mesh
  79972. _this.reconstructMesh(submeshIndex);
  79973. successCallback();
  79974. }, 0);
  79975. });
  79976. };
  79977. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  79978. var _this = this;
  79979. this.vertices = [];
  79980. this.triangles = [];
  79981. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  79982. var indices = this._mesh.getIndices();
  79983. var submesh = this._mesh.subMeshes[submeshIndex];
  79984. var findInVertices = function (positionToSearch) {
  79985. if (optimizeMesh) {
  79986. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  79987. if (_this.vertices[ii].position.equals(positionToSearch)) {
  79988. return _this.vertices[ii];
  79989. }
  79990. }
  79991. }
  79992. return null;
  79993. };
  79994. var vertexReferences = [];
  79995. var vertexInit = function (i) {
  79996. if (!positionData) {
  79997. return;
  79998. }
  79999. var offset = i + submesh.verticesStart;
  80000. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  80001. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  80002. vertex.originalOffsets.push(offset);
  80003. if (vertex.id === _this.vertices.length) {
  80004. _this.vertices.push(vertex);
  80005. }
  80006. vertexReferences.push(vertex.id);
  80007. };
  80008. //var totalVertices = mesh.getTotalVertices();
  80009. var totalVertices = submesh.verticesCount;
  80010. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  80011. var indicesInit = function (i) {
  80012. if (!indices) {
  80013. return;
  80014. }
  80015. var offset = (submesh.indexStart / 3) + i;
  80016. var pos = (offset * 3);
  80017. var i0 = indices[pos + 0];
  80018. var i1 = indices[pos + 1];
  80019. var i2 = indices[pos + 2];
  80020. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  80021. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  80022. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  80023. var triangle = new DecimationTriangle([v0, v1, v2]);
  80024. triangle.originalOffset = pos;
  80025. _this.triangles.push(triangle);
  80026. };
  80027. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  80028. _this.init(callback);
  80029. });
  80030. });
  80031. };
  80032. QuadraticErrorSimplification.prototype.init = function (callback) {
  80033. var _this = this;
  80034. var triangleInit1 = function (i) {
  80035. var t = _this.triangles[i];
  80036. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  80037. for (var j = 0; j < 3; j++) {
  80038. 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))));
  80039. }
  80040. };
  80041. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  80042. var triangleInit2 = function (i) {
  80043. var t = _this.triangles[i];
  80044. for (var j = 0; j < 3; ++j) {
  80045. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  80046. }
  80047. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  80048. };
  80049. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  80050. callback();
  80051. });
  80052. });
  80053. };
  80054. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  80055. var newTriangles = [];
  80056. var i;
  80057. for (i = 0; i < this.vertices.length; ++i) {
  80058. this.vertices[i].triangleCount = 0;
  80059. }
  80060. var t;
  80061. var j;
  80062. for (i = 0; i < this.triangles.length; ++i) {
  80063. if (!this.triangles[i].deleted) {
  80064. t = this.triangles[i];
  80065. for (j = 0; j < 3; ++j) {
  80066. t.vertices[j].triangleCount = 1;
  80067. }
  80068. newTriangles.push(t);
  80069. }
  80070. }
  80071. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  80072. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  80073. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  80074. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  80075. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  80076. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  80077. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  80078. var vertexCount = 0;
  80079. for (i = 0; i < this.vertices.length; ++i) {
  80080. var vertex = this.vertices[i];
  80081. vertex.id = vertexCount;
  80082. if (vertex.triangleCount) {
  80083. vertex.originalOffsets.forEach(function (originalOffset) {
  80084. if (!normalData) {
  80085. return;
  80086. }
  80087. newPositionData.push(vertex.position.x);
  80088. newPositionData.push(vertex.position.y);
  80089. newPositionData.push(vertex.position.z);
  80090. newNormalData.push(normalData[originalOffset * 3]);
  80091. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  80092. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  80093. if (uvs && uvs.length) {
  80094. newUVsData.push(uvs[(originalOffset * 2)]);
  80095. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  80096. }
  80097. else if (colorsData && colorsData.length) {
  80098. newColorsData.push(colorsData[(originalOffset * 4)]);
  80099. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  80100. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  80101. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  80102. }
  80103. ++vertexCount;
  80104. });
  80105. }
  80106. }
  80107. var startingIndex = this._reconstructedMesh.getTotalIndices();
  80108. var startingVertex = this._reconstructedMesh.getTotalVertices();
  80109. var submeshesArray = this._reconstructedMesh.subMeshes;
  80110. this._reconstructedMesh.subMeshes = [];
  80111. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  80112. var originalIndices = this._mesh.getIndices();
  80113. for (i = 0; i < newTriangles.length; ++i) {
  80114. t = newTriangles[i]; //now get the new referencing point for each vertex
  80115. [0, 1, 2].forEach(function (idx) {
  80116. var id = originalIndices[t.originalOffset + idx];
  80117. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  80118. if (offset < 0)
  80119. offset = 0;
  80120. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  80121. });
  80122. }
  80123. //overwriting the old vertex buffers and indices.
  80124. this._reconstructedMesh.setIndices(newIndicesArray);
  80125. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  80126. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  80127. if (newUVsData.length > 0)
  80128. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  80129. if (newColorsData.length > 0)
  80130. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  80131. //create submesh
  80132. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  80133. if (submeshIndex > 0) {
  80134. this._reconstructedMesh.subMeshes = [];
  80135. submeshesArray.forEach(function (submesh) {
  80136. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  80137. });
  80138. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  80139. }
  80140. };
  80141. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  80142. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  80143. this._reconstructedMesh.material = this._mesh.material;
  80144. this._reconstructedMesh.parent = this._mesh.parent;
  80145. this._reconstructedMesh.isVisible = false;
  80146. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  80147. };
  80148. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  80149. for (var i = 0; i < vertex1.triangleCount; ++i) {
  80150. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  80151. if (t.deleted)
  80152. continue;
  80153. var s = this.references[vertex1.triangleStart + i].vertexId;
  80154. var v1 = t.vertices[(s + 1) % 3];
  80155. var v2 = t.vertices[(s + 2) % 3];
  80156. if ((v1 === vertex2 || v2 === vertex2)) {
  80157. deletedArray[i] = true;
  80158. delTr.push(t);
  80159. continue;
  80160. }
  80161. var d1 = v1.position.subtract(point);
  80162. d1 = d1.normalize();
  80163. var d2 = v2.position.subtract(point);
  80164. d2 = d2.normalize();
  80165. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  80166. return true;
  80167. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  80168. deletedArray[i] = false;
  80169. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  80170. return true;
  80171. }
  80172. return false;
  80173. };
  80174. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  80175. var newDeleted = deletedTriangles;
  80176. for (var i = 0; i < vertex.triangleCount; ++i) {
  80177. var ref = this.references[vertex.triangleStart + i];
  80178. var t = this.triangles[ref.triangleId];
  80179. if (t.deleted)
  80180. continue;
  80181. if (deletedArray[i] && t.deletePending) {
  80182. t.deleted = true;
  80183. newDeleted++;
  80184. continue;
  80185. }
  80186. t.vertices[ref.vertexId] = origVertex;
  80187. t.isDirty = true;
  80188. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  80189. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  80190. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  80191. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  80192. this.references.push(ref);
  80193. }
  80194. return newDeleted;
  80195. };
  80196. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  80197. for (var i = 0; i < this.vertices.length; ++i) {
  80198. var vCount = [];
  80199. var vId = [];
  80200. var v = this.vertices[i];
  80201. var j;
  80202. for (j = 0; j < v.triangleCount; ++j) {
  80203. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  80204. for (var ii = 0; ii < 3; ii++) {
  80205. var ofs = 0;
  80206. var vv = triangle.vertices[ii];
  80207. while (ofs < vCount.length) {
  80208. if (vId[ofs] === vv.id)
  80209. break;
  80210. ++ofs;
  80211. }
  80212. if (ofs === vCount.length) {
  80213. vCount.push(1);
  80214. vId.push(vv.id);
  80215. }
  80216. else {
  80217. vCount[ofs]++;
  80218. }
  80219. }
  80220. }
  80221. for (j = 0; j < vCount.length; ++j) {
  80222. if (vCount[j] === 1) {
  80223. this.vertices[vId[j]].isBorder = true;
  80224. }
  80225. else {
  80226. this.vertices[vId[j]].isBorder = false;
  80227. }
  80228. }
  80229. }
  80230. };
  80231. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  80232. if (identifyBorders === void 0) { identifyBorders = false; }
  80233. var i;
  80234. if (!identifyBorders) {
  80235. var newTrianglesVector = [];
  80236. for (i = 0; i < this.triangles.length; ++i) {
  80237. if (!this.triangles[i].deleted) {
  80238. newTrianglesVector.push(this.triangles[i]);
  80239. }
  80240. }
  80241. this.triangles = newTrianglesVector;
  80242. }
  80243. for (i = 0; i < this.vertices.length; ++i) {
  80244. this.vertices[i].triangleCount = 0;
  80245. this.vertices[i].triangleStart = 0;
  80246. }
  80247. var t;
  80248. var j;
  80249. var v;
  80250. for (i = 0; i < this.triangles.length; ++i) {
  80251. t = this.triangles[i];
  80252. for (j = 0; j < 3; ++j) {
  80253. v = t.vertices[j];
  80254. v.triangleCount++;
  80255. }
  80256. }
  80257. var tStart = 0;
  80258. for (i = 0; i < this.vertices.length; ++i) {
  80259. this.vertices[i].triangleStart = tStart;
  80260. tStart += this.vertices[i].triangleCount;
  80261. this.vertices[i].triangleCount = 0;
  80262. }
  80263. var newReferences = new Array(this.triangles.length * 3);
  80264. for (i = 0; i < this.triangles.length; ++i) {
  80265. t = this.triangles[i];
  80266. for (j = 0; j < 3; ++j) {
  80267. v = t.vertices[j];
  80268. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  80269. v.triangleCount++;
  80270. }
  80271. }
  80272. this.references = newReferences;
  80273. if (identifyBorders) {
  80274. this.identifyBorder();
  80275. }
  80276. };
  80277. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  80278. var x = point.x;
  80279. var y = point.y;
  80280. var z = point.z;
  80281. 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
  80282. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  80283. };
  80284. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  80285. var q = vertex1.q.add(vertex2.q);
  80286. var border = vertex1.isBorder && vertex2.isBorder;
  80287. var error = 0;
  80288. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  80289. if (qDet !== 0 && !border) {
  80290. if (!pointResult) {
  80291. pointResult = BABYLON.Vector3.Zero();
  80292. }
  80293. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  80294. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  80295. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  80296. error = this.vertexError(q, pointResult);
  80297. }
  80298. else {
  80299. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  80300. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  80301. var error1 = this.vertexError(q, vertex1.position);
  80302. var error2 = this.vertexError(q, vertex2.position);
  80303. var error3 = this.vertexError(q, p3);
  80304. error = Math.min(error1, error2, error3);
  80305. if (error === error1) {
  80306. if (pointResult) {
  80307. pointResult.copyFrom(vertex1.position);
  80308. }
  80309. }
  80310. else if (error === error2) {
  80311. if (pointResult) {
  80312. pointResult.copyFrom(vertex2.position);
  80313. }
  80314. }
  80315. else {
  80316. if (pointResult) {
  80317. pointResult.copyFrom(p3);
  80318. }
  80319. }
  80320. }
  80321. return error;
  80322. };
  80323. return QuadraticErrorSimplification;
  80324. }());
  80325. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  80326. })(BABYLON || (BABYLON = {}));
  80327. //# sourceMappingURL=babylon.meshSimplification.js.map
  80328. var BABYLON;
  80329. (function (BABYLON) {
  80330. var MeshLODLevel = /** @class */ (function () {
  80331. function MeshLODLevel(distance, mesh) {
  80332. this.distance = distance;
  80333. this.mesh = mesh;
  80334. }
  80335. return MeshLODLevel;
  80336. }());
  80337. BABYLON.MeshLODLevel = MeshLODLevel;
  80338. })(BABYLON || (BABYLON = {}));
  80339. //# sourceMappingURL=babylon.meshLODLevel.js.map
  80340. var BABYLON;
  80341. (function (BABYLON) {
  80342. /**
  80343. * Defines the root class used to create scene optimization to use with SceneOptimizer
  80344. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80345. */
  80346. var SceneOptimization = /** @class */ (function () {
  80347. /**
  80348. * Creates the SceneOptimization object
  80349. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  80350. * @param desc defines the description associated with the optimization
  80351. */
  80352. function SceneOptimization(
  80353. /**
  80354. * Defines the priority of this optimization (0 by default which means first in the list)
  80355. */
  80356. priority) {
  80357. if (priority === void 0) { priority = 0; }
  80358. this.priority = priority;
  80359. }
  80360. /**
  80361. * Gets a string describing the action executed by the current optimization
  80362. * @returns description string
  80363. */
  80364. SceneOptimization.prototype.getDescription = function () {
  80365. return "";
  80366. };
  80367. /**
  80368. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  80369. * @param scene defines the current scene where to apply this optimization
  80370. * @param optimizer defines the current optimizer
  80371. * @returns true if everything that can be done was applied
  80372. */
  80373. SceneOptimization.prototype.apply = function (scene, optimizer) {
  80374. return true;
  80375. };
  80376. ;
  80377. return SceneOptimization;
  80378. }());
  80379. BABYLON.SceneOptimization = SceneOptimization;
  80380. /**
  80381. * Defines an optimization used to reduce the size of render target textures
  80382. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80383. */
  80384. var TextureOptimization = /** @class */ (function (_super) {
  80385. __extends(TextureOptimization, _super);
  80386. /**
  80387. * Creates the TextureOptimization object
  80388. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  80389. * @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
  80390. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  80391. */
  80392. function TextureOptimization(
  80393. /**
  80394. * Defines the priority of this optimization (0 by default which means first in the list)
  80395. */
  80396. priority,
  80397. /**
  80398. * 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
  80399. */
  80400. maximumSize,
  80401. /**
  80402. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  80403. */
  80404. step) {
  80405. if (priority === void 0) { priority = 0; }
  80406. if (maximumSize === void 0) { maximumSize = 1024; }
  80407. if (step === void 0) { step = 0.5; }
  80408. var _this = _super.call(this, priority) || this;
  80409. _this.priority = priority;
  80410. _this.maximumSize = maximumSize;
  80411. _this.step = step;
  80412. return _this;
  80413. }
  80414. /**
  80415. * Gets a string describing the action executed by the current optimization
  80416. * @returns description string
  80417. */
  80418. TextureOptimization.prototype.getDescription = function () {
  80419. return "Reducing render target texture size to " + this.maximumSize;
  80420. };
  80421. /**
  80422. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  80423. * @param scene defines the current scene where to apply this optimization
  80424. * @param optimizer defines the current optimizer
  80425. * @returns true if everything that can be done was applied
  80426. */
  80427. TextureOptimization.prototype.apply = function (scene, optimizer) {
  80428. var allDone = true;
  80429. for (var index = 0; index < scene.textures.length; index++) {
  80430. var texture = scene.textures[index];
  80431. if (!texture.canRescale || texture.getContext) {
  80432. continue;
  80433. }
  80434. var currentSize = texture.getSize();
  80435. var maxDimension = Math.max(currentSize.width, currentSize.height);
  80436. if (maxDimension > this.maximumSize) {
  80437. texture.scale(this.step);
  80438. allDone = false;
  80439. }
  80440. }
  80441. return allDone;
  80442. };
  80443. return TextureOptimization;
  80444. }(SceneOptimization));
  80445. BABYLON.TextureOptimization = TextureOptimization;
  80446. /**
  80447. * Defines an optimization used to increase or decrease the rendering resolution
  80448. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80449. */
  80450. var HardwareScalingOptimization = /** @class */ (function (_super) {
  80451. __extends(HardwareScalingOptimization, _super);
  80452. /**
  80453. * Creates the HardwareScalingOptimization object
  80454. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  80455. * @param maximumScale defines the maximum scale to use (2 by default)
  80456. * @param step defines the step to use between two passes (0.5 by default)
  80457. */
  80458. function HardwareScalingOptimization(
  80459. /**
  80460. * Defines the priority of this optimization (0 by default which means first in the list)
  80461. */
  80462. priority,
  80463. /**
  80464. * Defines the maximum scale to use (2 by default)
  80465. */
  80466. maximumScale,
  80467. /**
  80468. * Defines the step to use between two passes (0.5 by default)
  80469. */
  80470. step) {
  80471. if (priority === void 0) { priority = 0; }
  80472. if (maximumScale === void 0) { maximumScale = 2; }
  80473. if (step === void 0) { step = 0.25; }
  80474. var _this = _super.call(this, priority) || this;
  80475. _this.priority = priority;
  80476. _this.maximumScale = maximumScale;
  80477. _this.step = step;
  80478. _this._currentScale = -1;
  80479. _this._directionOffset = 1;
  80480. return _this;
  80481. }
  80482. /**
  80483. * Gets a string describing the action executed by the current optimization
  80484. * @return description string
  80485. */
  80486. HardwareScalingOptimization.prototype.getDescription = function () {
  80487. return "Setting hardware scaling level to " + this._currentScale;
  80488. };
  80489. /**
  80490. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  80491. * @param scene defines the current scene where to apply this optimization
  80492. * @param optimizer defines the current optimizer
  80493. * @returns true if everything that can be done was applied
  80494. */
  80495. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  80496. if (this._currentScale === -1) {
  80497. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  80498. if (this._currentScale > this.maximumScale) {
  80499. this._directionOffset = -1;
  80500. }
  80501. }
  80502. this._currentScale += this._directionOffset * this.step;
  80503. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  80504. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  80505. };
  80506. ;
  80507. return HardwareScalingOptimization;
  80508. }(SceneOptimization));
  80509. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  80510. /**
  80511. * Defines an optimization used to remove shadows
  80512. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80513. */
  80514. var ShadowsOptimization = /** @class */ (function (_super) {
  80515. __extends(ShadowsOptimization, _super);
  80516. function ShadowsOptimization() {
  80517. return _super !== null && _super.apply(this, arguments) || this;
  80518. }
  80519. /**
  80520. * Gets a string describing the action executed by the current optimization
  80521. * @return description string
  80522. */
  80523. ShadowsOptimization.prototype.getDescription = function () {
  80524. return "Turning shadows on/off";
  80525. };
  80526. /**
  80527. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  80528. * @param scene defines the current scene where to apply this optimization
  80529. * @param optimizer defines the current optimizer
  80530. * @returns true if everything that can be done was applied
  80531. */
  80532. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  80533. scene.shadowsEnabled = optimizer.isInImprovementMode;
  80534. return true;
  80535. };
  80536. ;
  80537. return ShadowsOptimization;
  80538. }(SceneOptimization));
  80539. BABYLON.ShadowsOptimization = ShadowsOptimization;
  80540. /**
  80541. * Defines an optimization used to turn post-processes off
  80542. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80543. */
  80544. var PostProcessesOptimization = /** @class */ (function (_super) {
  80545. __extends(PostProcessesOptimization, _super);
  80546. function PostProcessesOptimization() {
  80547. return _super !== null && _super.apply(this, arguments) || this;
  80548. }
  80549. /**
  80550. * Gets a string describing the action executed by the current optimization
  80551. * @return description string
  80552. */
  80553. PostProcessesOptimization.prototype.getDescription = function () {
  80554. return "Turning post-processes on/off";
  80555. };
  80556. /**
  80557. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  80558. * @param scene defines the current scene where to apply this optimization
  80559. * @param optimizer defines the current optimizer
  80560. * @returns true if everything that can be done was applied
  80561. */
  80562. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  80563. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  80564. return true;
  80565. };
  80566. ;
  80567. return PostProcessesOptimization;
  80568. }(SceneOptimization));
  80569. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  80570. /**
  80571. * Defines an optimization used to turn lens flares off
  80572. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80573. */
  80574. var LensFlaresOptimization = /** @class */ (function (_super) {
  80575. __extends(LensFlaresOptimization, _super);
  80576. function LensFlaresOptimization() {
  80577. return _super !== null && _super.apply(this, arguments) || this;
  80578. }
  80579. /**
  80580. * Gets a string describing the action executed by the current optimization
  80581. * @return description string
  80582. */
  80583. LensFlaresOptimization.prototype.getDescription = function () {
  80584. return "Turning lens flares on/off";
  80585. };
  80586. /**
  80587. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  80588. * @param scene defines the current scene where to apply this optimization
  80589. * @param optimizer defines the current optimizer
  80590. * @returns true if everything that can be done was applied
  80591. */
  80592. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  80593. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  80594. return true;
  80595. };
  80596. ;
  80597. return LensFlaresOptimization;
  80598. }(SceneOptimization));
  80599. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  80600. /**
  80601. * Defines an optimization based on user defined callback.
  80602. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80603. */
  80604. var CustomOptimization = /** @class */ (function (_super) {
  80605. __extends(CustomOptimization, _super);
  80606. function CustomOptimization() {
  80607. return _super !== null && _super.apply(this, arguments) || this;
  80608. }
  80609. /**
  80610. * Gets a string describing the action executed by the current optimization
  80611. * @returns description string
  80612. */
  80613. CustomOptimization.prototype.getDescription = function () {
  80614. if (this.onGetDescription) {
  80615. return this.onGetDescription();
  80616. }
  80617. return "Running user defined callback";
  80618. };
  80619. /**
  80620. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  80621. * @param scene defines the current scene where to apply this optimization
  80622. * @param optimizer defines the current optimizer
  80623. * @returns true if everything that can be done was applied
  80624. */
  80625. CustomOptimization.prototype.apply = function (scene, optimizer) {
  80626. if (this.onApply) {
  80627. return this.onApply(scene, optimizer);
  80628. }
  80629. return true;
  80630. };
  80631. ;
  80632. return CustomOptimization;
  80633. }(SceneOptimization));
  80634. BABYLON.CustomOptimization = CustomOptimization;
  80635. /**
  80636. * Defines an optimization used to turn particles off
  80637. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80638. */
  80639. var ParticlesOptimization = /** @class */ (function (_super) {
  80640. __extends(ParticlesOptimization, _super);
  80641. function ParticlesOptimization() {
  80642. return _super !== null && _super.apply(this, arguments) || this;
  80643. }
  80644. /**
  80645. * Gets a string describing the action executed by the current optimization
  80646. * @return description string
  80647. */
  80648. ParticlesOptimization.prototype.getDescription = function () {
  80649. return "Turning particles on/off";
  80650. };
  80651. /**
  80652. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  80653. * @param scene defines the current scene where to apply this optimization
  80654. * @param optimizer defines the current optimizer
  80655. * @returns true if everything that can be done was applied
  80656. */
  80657. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  80658. scene.particlesEnabled = optimizer.isInImprovementMode;
  80659. return true;
  80660. };
  80661. ;
  80662. return ParticlesOptimization;
  80663. }(SceneOptimization));
  80664. BABYLON.ParticlesOptimization = ParticlesOptimization;
  80665. /**
  80666. * Defines an optimization used to turn render targets off
  80667. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80668. */
  80669. var RenderTargetsOptimization = /** @class */ (function (_super) {
  80670. __extends(RenderTargetsOptimization, _super);
  80671. function RenderTargetsOptimization() {
  80672. return _super !== null && _super.apply(this, arguments) || this;
  80673. }
  80674. /**
  80675. * Gets a string describing the action executed by the current optimization
  80676. * @return description string
  80677. */
  80678. RenderTargetsOptimization.prototype.getDescription = function () {
  80679. return "Turning render targets off";
  80680. };
  80681. /**
  80682. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  80683. * @param scene defines the current scene where to apply this optimization
  80684. * @param optimizer defines the current optimizer
  80685. * @returns true if everything that can be done was applied
  80686. */
  80687. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  80688. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  80689. return true;
  80690. };
  80691. ;
  80692. return RenderTargetsOptimization;
  80693. }(SceneOptimization));
  80694. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  80695. /**
  80696. * Defines an optimization used to merge meshes with compatible materials
  80697. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80698. */
  80699. var MergeMeshesOptimization = /** @class */ (function (_super) {
  80700. __extends(MergeMeshesOptimization, _super);
  80701. function MergeMeshesOptimization() {
  80702. var _this = _super !== null && _super.apply(this, arguments) || this;
  80703. _this._canBeMerged = function (abstractMesh) {
  80704. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  80705. return false;
  80706. }
  80707. var mesh = abstractMesh;
  80708. if (!mesh.isVisible || !mesh.isEnabled()) {
  80709. return false;
  80710. }
  80711. if (mesh.instances.length > 0) {
  80712. return false;
  80713. }
  80714. if (mesh.skeleton || mesh.hasLODLevels) {
  80715. return false;
  80716. }
  80717. if (mesh.parent) {
  80718. return false;
  80719. }
  80720. return true;
  80721. };
  80722. return _this;
  80723. }
  80724. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  80725. /**
  80726. * Gets or sets a boolean which defines if optimization octree has to be updated
  80727. */
  80728. get: function () {
  80729. return MergeMeshesOptimization._UpdateSelectionTree;
  80730. },
  80731. /**
  80732. * Gets or sets a boolean which defines if optimization octree has to be updated
  80733. */
  80734. set: function (value) {
  80735. MergeMeshesOptimization._UpdateSelectionTree = value;
  80736. },
  80737. enumerable: true,
  80738. configurable: true
  80739. });
  80740. /**
  80741. * Gets a string describing the action executed by the current optimization
  80742. * @return description string
  80743. */
  80744. MergeMeshesOptimization.prototype.getDescription = function () {
  80745. return "Merging similar meshes together";
  80746. };
  80747. /**
  80748. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  80749. * @param scene defines the current scene where to apply this optimization
  80750. * @param optimizer defines the current optimizer
  80751. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  80752. * @returns true if everything that can be done was applied
  80753. */
  80754. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  80755. var globalPool = scene.meshes.slice(0);
  80756. var globalLength = globalPool.length;
  80757. for (var index = 0; index < globalLength; index++) {
  80758. var currentPool = new Array();
  80759. var current = globalPool[index];
  80760. // Checks
  80761. if (!this._canBeMerged(current)) {
  80762. continue;
  80763. }
  80764. currentPool.push(current);
  80765. // Find compatible meshes
  80766. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  80767. var otherMesh = globalPool[subIndex];
  80768. if (!this._canBeMerged(otherMesh)) {
  80769. continue;
  80770. }
  80771. if (otherMesh.material !== current.material) {
  80772. continue;
  80773. }
  80774. if (otherMesh.checkCollisions !== current.checkCollisions) {
  80775. continue;
  80776. }
  80777. currentPool.push(otherMesh);
  80778. globalLength--;
  80779. globalPool.splice(subIndex, 1);
  80780. subIndex--;
  80781. }
  80782. if (currentPool.length < 2) {
  80783. continue;
  80784. }
  80785. // Merge meshes
  80786. BABYLON.Mesh.MergeMeshes(currentPool);
  80787. }
  80788. if (updateSelectionTree != undefined) {
  80789. if (updateSelectionTree) {
  80790. scene.createOrUpdateSelectionOctree();
  80791. }
  80792. }
  80793. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  80794. scene.createOrUpdateSelectionOctree();
  80795. }
  80796. return true;
  80797. };
  80798. ;
  80799. MergeMeshesOptimization._UpdateSelectionTree = false;
  80800. return MergeMeshesOptimization;
  80801. }(SceneOptimization));
  80802. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  80803. /**
  80804. * Defines a list of options used by SceneOptimizer
  80805. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80806. */
  80807. var SceneOptimizerOptions = /** @class */ (function () {
  80808. /**
  80809. * Creates a new list of options used by SceneOptimizer
  80810. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  80811. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  80812. */
  80813. function SceneOptimizerOptions(
  80814. /**
  80815. * Defines the target frame rate to reach (60 by default)
  80816. */
  80817. targetFrameRate,
  80818. /**
  80819. * Defines the interval between two checkes (2000ms by default)
  80820. */
  80821. trackerDuration) {
  80822. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  80823. if (trackerDuration === void 0) { trackerDuration = 2000; }
  80824. this.targetFrameRate = targetFrameRate;
  80825. this.trackerDuration = trackerDuration;
  80826. /**
  80827. * Gets the list of optimizations to apply
  80828. */
  80829. this.optimizations = new Array();
  80830. }
  80831. /**
  80832. * Add a new optimization
  80833. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  80834. * @returns the current SceneOptimizerOptions
  80835. */
  80836. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  80837. this.optimizations.push(optimization);
  80838. return this;
  80839. };
  80840. /**
  80841. * Add a new custom optimization
  80842. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  80843. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  80844. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  80845. * @returns the current SceneOptimizerOptions
  80846. */
  80847. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  80848. if (priority === void 0) { priority = 0; }
  80849. var optimization = new CustomOptimization(priority);
  80850. optimization.onApply = onApply;
  80851. optimization.onGetDescription = onGetDescription;
  80852. this.optimizations.push(optimization);
  80853. return this;
  80854. };
  80855. /**
  80856. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  80857. * @param targetFrameRate defines the target frame rate (60 by default)
  80858. * @returns a SceneOptimizerOptions object
  80859. */
  80860. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  80861. var result = new SceneOptimizerOptions(targetFrameRate);
  80862. var priority = 0;
  80863. result.addOptimization(new MergeMeshesOptimization(priority));
  80864. result.addOptimization(new ShadowsOptimization(priority));
  80865. result.addOptimization(new LensFlaresOptimization(priority));
  80866. // Next priority
  80867. priority++;
  80868. result.addOptimization(new PostProcessesOptimization(priority));
  80869. result.addOptimization(new ParticlesOptimization(priority));
  80870. // Next priority
  80871. priority++;
  80872. result.addOptimization(new TextureOptimization(priority, 1024));
  80873. return result;
  80874. };
  80875. /**
  80876. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  80877. * @param targetFrameRate defines the target frame rate (60 by default)
  80878. * @returns a SceneOptimizerOptions object
  80879. */
  80880. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  80881. var result = new SceneOptimizerOptions(targetFrameRate);
  80882. var priority = 0;
  80883. result.addOptimization(new MergeMeshesOptimization(priority));
  80884. result.addOptimization(new ShadowsOptimization(priority));
  80885. result.addOptimization(new LensFlaresOptimization(priority));
  80886. // Next priority
  80887. priority++;
  80888. result.addOptimization(new PostProcessesOptimization(priority));
  80889. result.addOptimization(new ParticlesOptimization(priority));
  80890. // Next priority
  80891. priority++;
  80892. result.addOptimization(new TextureOptimization(priority, 512));
  80893. // Next priority
  80894. priority++;
  80895. result.addOptimization(new RenderTargetsOptimization(priority));
  80896. // Next priority
  80897. priority++;
  80898. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  80899. return result;
  80900. };
  80901. /**
  80902. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  80903. * @param targetFrameRate defines the target frame rate (60 by default)
  80904. * @returns a SceneOptimizerOptions object
  80905. */
  80906. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  80907. var result = new SceneOptimizerOptions(targetFrameRate);
  80908. var priority = 0;
  80909. result.addOptimization(new MergeMeshesOptimization(priority));
  80910. result.addOptimization(new ShadowsOptimization(priority));
  80911. result.addOptimization(new LensFlaresOptimization(priority));
  80912. // Next priority
  80913. priority++;
  80914. result.addOptimization(new PostProcessesOptimization(priority));
  80915. result.addOptimization(new ParticlesOptimization(priority));
  80916. // Next priority
  80917. priority++;
  80918. result.addOptimization(new TextureOptimization(priority, 256));
  80919. // Next priority
  80920. priority++;
  80921. result.addOptimization(new RenderTargetsOptimization(priority));
  80922. // Next priority
  80923. priority++;
  80924. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  80925. return result;
  80926. };
  80927. return SceneOptimizerOptions;
  80928. }());
  80929. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  80930. /**
  80931. * Class used to run optimizations in order to reach a target frame rate
  80932. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80933. */
  80934. var SceneOptimizer = /** @class */ (function () {
  80935. /**
  80936. * Creates a new SceneOptimizer
  80937. * @param scene defines the scene to work on
  80938. * @param options defines the options to use with the SceneOptimizer
  80939. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  80940. * @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)
  80941. */
  80942. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  80943. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  80944. if (improvementMode === void 0) { improvementMode = false; }
  80945. var _this = this;
  80946. this._isRunning = false;
  80947. this._currentPriorityLevel = 0;
  80948. this._targetFrameRate = 60;
  80949. this._trackerDuration = 2000;
  80950. this._currentFrameRate = 0;
  80951. this._improvementMode = false;
  80952. /**
  80953. * Defines an observable called when the optimizer reaches the target frame rate
  80954. */
  80955. this.onSuccessObservable = new BABYLON.Observable();
  80956. /**
  80957. * Defines an observable called when the optimizer enables an optimization
  80958. */
  80959. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  80960. /**
  80961. * Defines an observable called when the optimizer is not able to reach the target frame rate
  80962. */
  80963. this.onFailureObservable = new BABYLON.Observable();
  80964. if (!options) {
  80965. this._options = new SceneOptimizerOptions();
  80966. }
  80967. else {
  80968. this._options = options;
  80969. }
  80970. if (this._options.targetFrameRate) {
  80971. this._targetFrameRate = this._options.targetFrameRate;
  80972. }
  80973. if (this._options.trackerDuration) {
  80974. this._trackerDuration = this._options.trackerDuration;
  80975. }
  80976. if (autoGeneratePriorities) {
  80977. var priority = 0;
  80978. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  80979. var optim = _a[_i];
  80980. optim.priority = priority++;
  80981. }
  80982. }
  80983. this._improvementMode = improvementMode;
  80984. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80985. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  80986. _this._sceneDisposeObserver = null;
  80987. _this.dispose();
  80988. });
  80989. }
  80990. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  80991. /**
  80992. * Gets a boolean indicating if the optimizer is in improvement mode
  80993. */
  80994. get: function () {
  80995. return this._improvementMode;
  80996. },
  80997. enumerable: true,
  80998. configurable: true
  80999. });
  81000. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  81001. /**
  81002. * Gets the current priority level (0 at start)
  81003. */
  81004. get: function () {
  81005. return this._currentPriorityLevel;
  81006. },
  81007. enumerable: true,
  81008. configurable: true
  81009. });
  81010. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  81011. /**
  81012. * Gets the current frame rate checked by the SceneOptimizer
  81013. */
  81014. get: function () {
  81015. return this._currentFrameRate;
  81016. },
  81017. enumerable: true,
  81018. configurable: true
  81019. });
  81020. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  81021. /**
  81022. * Gets or sets the current target frame rate (60 by default)
  81023. */
  81024. get: function () {
  81025. return this._targetFrameRate;
  81026. },
  81027. /**
  81028. * Gets or sets the current target frame rate (60 by default)
  81029. */
  81030. set: function (value) {
  81031. this._targetFrameRate = value;
  81032. },
  81033. enumerable: true,
  81034. configurable: true
  81035. });
  81036. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  81037. /**
  81038. * Gets or sets the current interval between two checks (every 2000ms by default)
  81039. */
  81040. get: function () {
  81041. return this._trackerDuration;
  81042. },
  81043. /**
  81044. * Gets or sets the current interval between two checks (every 2000ms by default)
  81045. */
  81046. set: function (value) {
  81047. this._trackerDuration = value;
  81048. },
  81049. enumerable: true,
  81050. configurable: true
  81051. });
  81052. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  81053. /**
  81054. * Gets the list of active optimizations
  81055. */
  81056. get: function () {
  81057. return this._options.optimizations;
  81058. },
  81059. enumerable: true,
  81060. configurable: true
  81061. });
  81062. /**
  81063. * Stops the current optimizer
  81064. */
  81065. SceneOptimizer.prototype.stop = function () {
  81066. this._isRunning = false;
  81067. };
  81068. /**
  81069. * Reset the optimizer to initial step (current priority level = 0)
  81070. */
  81071. SceneOptimizer.prototype.reset = function () {
  81072. this._currentPriorityLevel = 0;
  81073. };
  81074. /**
  81075. * Start the optimizer. By default it will try to reach a specific framerate
  81076. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  81077. */
  81078. SceneOptimizer.prototype.start = function () {
  81079. var _this = this;
  81080. if (this._isRunning) {
  81081. return;
  81082. }
  81083. this._isRunning = true;
  81084. // Let's wait for the scene to be ready before running our check
  81085. this._scene.executeWhenReady(function () {
  81086. setTimeout(function () {
  81087. _this._checkCurrentState();
  81088. }, _this._trackerDuration);
  81089. });
  81090. };
  81091. SceneOptimizer.prototype._checkCurrentState = function () {
  81092. var _this = this;
  81093. if (!this._isRunning) {
  81094. return;
  81095. }
  81096. var scene = this._scene;
  81097. var options = this._options;
  81098. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  81099. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  81100. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  81101. this._isRunning = false;
  81102. this.onSuccessObservable.notifyObservers(this);
  81103. return;
  81104. }
  81105. // Apply current level of optimizations
  81106. var allDone = true;
  81107. var noOptimizationApplied = true;
  81108. for (var index = 0; index < options.optimizations.length; index++) {
  81109. var optimization = options.optimizations[index];
  81110. if (optimization.priority === this._currentPriorityLevel) {
  81111. noOptimizationApplied = false;
  81112. allDone = allDone && optimization.apply(scene, this);
  81113. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  81114. }
  81115. }
  81116. // If no optimization was applied, this is a failure :(
  81117. if (noOptimizationApplied) {
  81118. this._isRunning = false;
  81119. this.onFailureObservable.notifyObservers(this);
  81120. return;
  81121. }
  81122. // If all optimizations were done, move to next level
  81123. if (allDone) {
  81124. this._currentPriorityLevel++;
  81125. }
  81126. // Let's the system running for a specific amount of time before checking FPS
  81127. scene.executeWhenReady(function () {
  81128. setTimeout(function () {
  81129. _this._checkCurrentState();
  81130. }, _this._trackerDuration);
  81131. });
  81132. };
  81133. /**
  81134. * Release all resources
  81135. */
  81136. SceneOptimizer.prototype.dispose = function () {
  81137. this.stop();
  81138. this.onSuccessObservable.clear();
  81139. this.onFailureObservable.clear();
  81140. this.onNewOptimizationAppliedObservable.clear();
  81141. if (this._sceneDisposeObserver) {
  81142. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  81143. }
  81144. };
  81145. /**
  81146. * Helper function to create a SceneOptimizer with one single line of code
  81147. * @param scene defines the scene to work on
  81148. * @param options defines the options to use with the SceneOptimizer
  81149. * @param onSuccess defines a callback to call on success
  81150. * @param onFailure defines a callback to call on failure
  81151. * @returns the new SceneOptimizer object
  81152. */
  81153. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  81154. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  81155. if (onSuccess) {
  81156. optimizer.onSuccessObservable.add(function () {
  81157. onSuccess();
  81158. });
  81159. }
  81160. if (onFailure) {
  81161. optimizer.onFailureObservable.add(function () {
  81162. onFailure();
  81163. });
  81164. }
  81165. optimizer.start();
  81166. return optimizer;
  81167. };
  81168. return SceneOptimizer;
  81169. }());
  81170. BABYLON.SceneOptimizer = SceneOptimizer;
  81171. })(BABYLON || (BABYLON = {}));
  81172. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  81173. var BABYLON;
  81174. (function (BABYLON) {
  81175. var OutlineRenderer = /** @class */ (function () {
  81176. function OutlineRenderer(scene) {
  81177. this.zOffset = 1;
  81178. this._scene = scene;
  81179. }
  81180. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  81181. var _this = this;
  81182. if (useOverlay === void 0) { useOverlay = false; }
  81183. var scene = this._scene;
  81184. var engine = this._scene.getEngine();
  81185. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  81186. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  81187. return;
  81188. }
  81189. var mesh = subMesh.getRenderingMesh();
  81190. var material = subMesh.getMaterial();
  81191. if (!material || !scene.activeCamera) {
  81192. return;
  81193. }
  81194. engine.enableEffect(this._effect);
  81195. // Logarithmic depth
  81196. if (material.useLogarithmicDepth) {
  81197. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  81198. }
  81199. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  81200. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  81201. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  81202. // Bones
  81203. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  81204. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  81205. }
  81206. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  81207. // Alpha test
  81208. if (material && material.needAlphaTesting()) {
  81209. var alphaTexture = material.getAlphaTestTexture();
  81210. if (alphaTexture) {
  81211. this._effect.setTexture("diffuseSampler", alphaTexture);
  81212. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  81213. }
  81214. }
  81215. engine.setZOffset(-this.zOffset);
  81216. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  81217. engine.setZOffset(0);
  81218. };
  81219. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  81220. var defines = [];
  81221. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  81222. var mesh = subMesh.getMesh();
  81223. var material = subMesh.getMaterial();
  81224. if (material) {
  81225. // Alpha test
  81226. if (material.needAlphaTesting()) {
  81227. defines.push("#define ALPHATEST");
  81228. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  81229. attribs.push(BABYLON.VertexBuffer.UVKind);
  81230. defines.push("#define UV1");
  81231. }
  81232. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  81233. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  81234. defines.push("#define UV2");
  81235. }
  81236. }
  81237. //Logarithmic depth
  81238. if (material.useLogarithmicDepth) {
  81239. defines.push("#define LOGARITHMICDEPTH");
  81240. }
  81241. }
  81242. // Bones
  81243. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  81244. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  81245. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  81246. if (mesh.numBoneInfluencers > 4) {
  81247. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  81248. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  81249. }
  81250. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  81251. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  81252. }
  81253. else {
  81254. defines.push("#define NUM_BONE_INFLUENCERS 0");
  81255. }
  81256. // Instances
  81257. if (useInstances) {
  81258. defines.push("#define INSTANCES");
  81259. attribs.push("world0");
  81260. attribs.push("world1");
  81261. attribs.push("world2");
  81262. attribs.push("world3");
  81263. }
  81264. // Get correct effect
  81265. var join = defines.join("\n");
  81266. if (this._cachedDefines !== join) {
  81267. this._cachedDefines = join;
  81268. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  81269. }
  81270. return this._effect.isReady();
  81271. };
  81272. return OutlineRenderer;
  81273. }());
  81274. BABYLON.OutlineRenderer = OutlineRenderer;
  81275. })(BABYLON || (BABYLON = {}));
  81276. //# sourceMappingURL=babylon.outlineRenderer.js.map
  81277. var BABYLON;
  81278. (function (BABYLON) {
  81279. var FaceAdjacencies = /** @class */ (function () {
  81280. function FaceAdjacencies() {
  81281. this.edges = new Array();
  81282. this.edgesConnectedCount = 0;
  81283. }
  81284. return FaceAdjacencies;
  81285. }());
  81286. var EdgesRenderer = /** @class */ (function () {
  81287. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  81288. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  81289. if (epsilon === void 0) { epsilon = 0.95; }
  81290. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  81291. this.edgesWidthScalerForOrthographic = 1000.0;
  81292. this.edgesWidthScalerForPerspective = 50.0;
  81293. this._linesPositions = new Array();
  81294. this._linesNormals = new Array();
  81295. this._linesIndices = new Array();
  81296. this._buffers = {};
  81297. this._checkVerticesInsteadOfIndices = false;
  81298. this._source = source;
  81299. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  81300. this._epsilon = epsilon;
  81301. this._prepareRessources();
  81302. this._generateEdgesLines();
  81303. }
  81304. EdgesRenderer.prototype._prepareRessources = function () {
  81305. if (this._lineShader) {
  81306. return;
  81307. }
  81308. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  81309. attributes: ["position", "normal"],
  81310. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  81311. });
  81312. this._lineShader.disableDepthWrite = true;
  81313. this._lineShader.backFaceCulling = false;
  81314. };
  81315. EdgesRenderer.prototype._rebuild = function () {
  81316. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  81317. if (buffer) {
  81318. buffer._rebuild();
  81319. }
  81320. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  81321. if (buffer) {
  81322. buffer._rebuild();
  81323. }
  81324. var scene = this._source.getScene();
  81325. var engine = scene.getEngine();
  81326. this._ib = engine.createIndexBuffer(this._linesIndices);
  81327. };
  81328. EdgesRenderer.prototype.dispose = function () {
  81329. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  81330. if (buffer) {
  81331. buffer.dispose();
  81332. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  81333. }
  81334. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  81335. if (buffer) {
  81336. buffer.dispose();
  81337. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  81338. }
  81339. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  81340. this._lineShader.dispose();
  81341. };
  81342. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  81343. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  81344. return 0;
  81345. }
  81346. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  81347. return 1;
  81348. }
  81349. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  81350. return 2;
  81351. }
  81352. return -1;
  81353. };
  81354. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  81355. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  81356. return 0;
  81357. }
  81358. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  81359. return 1;
  81360. }
  81361. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  81362. return 2;
  81363. }
  81364. return -1;
  81365. };
  81366. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  81367. var needToCreateLine;
  81368. if (edge === undefined) {
  81369. needToCreateLine = true;
  81370. }
  81371. else {
  81372. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  81373. needToCreateLine = dotProduct < this._epsilon;
  81374. }
  81375. if (needToCreateLine) {
  81376. var offset = this._linesPositions.length / 3;
  81377. var normal = p0.subtract(p1);
  81378. normal.normalize();
  81379. // Positions
  81380. this._linesPositions.push(p0.x);
  81381. this._linesPositions.push(p0.y);
  81382. this._linesPositions.push(p0.z);
  81383. this._linesPositions.push(p0.x);
  81384. this._linesPositions.push(p0.y);
  81385. this._linesPositions.push(p0.z);
  81386. this._linesPositions.push(p1.x);
  81387. this._linesPositions.push(p1.y);
  81388. this._linesPositions.push(p1.z);
  81389. this._linesPositions.push(p1.x);
  81390. this._linesPositions.push(p1.y);
  81391. this._linesPositions.push(p1.z);
  81392. // Normals
  81393. this._linesNormals.push(p1.x);
  81394. this._linesNormals.push(p1.y);
  81395. this._linesNormals.push(p1.z);
  81396. this._linesNormals.push(-1);
  81397. this._linesNormals.push(p1.x);
  81398. this._linesNormals.push(p1.y);
  81399. this._linesNormals.push(p1.z);
  81400. this._linesNormals.push(1);
  81401. this._linesNormals.push(p0.x);
  81402. this._linesNormals.push(p0.y);
  81403. this._linesNormals.push(p0.z);
  81404. this._linesNormals.push(-1);
  81405. this._linesNormals.push(p0.x);
  81406. this._linesNormals.push(p0.y);
  81407. this._linesNormals.push(p0.z);
  81408. this._linesNormals.push(1);
  81409. // Indices
  81410. this._linesIndices.push(offset);
  81411. this._linesIndices.push(offset + 1);
  81412. this._linesIndices.push(offset + 2);
  81413. this._linesIndices.push(offset);
  81414. this._linesIndices.push(offset + 2);
  81415. this._linesIndices.push(offset + 3);
  81416. }
  81417. };
  81418. EdgesRenderer.prototype._generateEdgesLines = function () {
  81419. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  81420. var indices = this._source.getIndices();
  81421. if (!indices || !positions) {
  81422. return;
  81423. }
  81424. // First let's find adjacencies
  81425. var adjacencies = new Array();
  81426. var faceNormals = new Array();
  81427. var index;
  81428. var faceAdjacencies;
  81429. // Prepare faces
  81430. for (index = 0; index < indices.length; index += 3) {
  81431. faceAdjacencies = new FaceAdjacencies();
  81432. var p0Index = indices[index];
  81433. var p1Index = indices[index + 1];
  81434. var p2Index = indices[index + 2];
  81435. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  81436. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  81437. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  81438. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  81439. faceNormal.normalize();
  81440. faceNormals.push(faceNormal);
  81441. adjacencies.push(faceAdjacencies);
  81442. }
  81443. // Scan
  81444. for (index = 0; index < adjacencies.length; index++) {
  81445. faceAdjacencies = adjacencies[index];
  81446. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  81447. var otherFaceAdjacencies = adjacencies[otherIndex];
  81448. if (faceAdjacencies.edgesConnectedCount === 3) {
  81449. break;
  81450. }
  81451. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  81452. continue;
  81453. }
  81454. var otherP0 = indices[otherIndex * 3];
  81455. var otherP1 = indices[otherIndex * 3 + 1];
  81456. var otherP2 = indices[otherIndex * 3 + 2];
  81457. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  81458. var otherEdgeIndex = 0;
  81459. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  81460. continue;
  81461. }
  81462. switch (edgeIndex) {
  81463. case 0:
  81464. if (this._checkVerticesInsteadOfIndices) {
  81465. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  81466. }
  81467. else {
  81468. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  81469. }
  81470. break;
  81471. case 1:
  81472. if (this._checkVerticesInsteadOfIndices) {
  81473. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  81474. }
  81475. else {
  81476. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  81477. }
  81478. break;
  81479. case 2:
  81480. if (this._checkVerticesInsteadOfIndices) {
  81481. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  81482. }
  81483. else {
  81484. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  81485. }
  81486. break;
  81487. }
  81488. if (otherEdgeIndex === -1) {
  81489. continue;
  81490. }
  81491. faceAdjacencies.edges[edgeIndex] = otherIndex;
  81492. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  81493. faceAdjacencies.edgesConnectedCount++;
  81494. otherFaceAdjacencies.edgesConnectedCount++;
  81495. if (faceAdjacencies.edgesConnectedCount === 3) {
  81496. break;
  81497. }
  81498. }
  81499. }
  81500. }
  81501. // Create lines
  81502. for (index = 0; index < adjacencies.length; index++) {
  81503. // 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
  81504. var current = adjacencies[index];
  81505. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  81506. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  81507. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  81508. }
  81509. // Merge into a single mesh
  81510. var engine = this._source.getScene().getEngine();
  81511. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  81512. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  81513. this._ib = engine.createIndexBuffer(this._linesIndices);
  81514. this._indicesCount = this._linesIndices.length;
  81515. };
  81516. EdgesRenderer.prototype.render = function () {
  81517. var scene = this._source.getScene();
  81518. if (!this._lineShader.isReady() || !scene.activeCamera) {
  81519. return;
  81520. }
  81521. var engine = scene.getEngine();
  81522. this._lineShader._preBind();
  81523. // VBOs
  81524. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  81525. scene.resetCachedMaterial();
  81526. this._lineShader.setColor4("color", this._source.edgesColor);
  81527. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  81528. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  81529. }
  81530. else {
  81531. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  81532. }
  81533. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  81534. this._lineShader.bind(this._source.getWorldMatrix());
  81535. // Draw order
  81536. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  81537. this._lineShader.unbind();
  81538. engine.setDepthWrite(true);
  81539. };
  81540. return EdgesRenderer;
  81541. }());
  81542. BABYLON.EdgesRenderer = EdgesRenderer;
  81543. })(BABYLON || (BABYLON = {}));
  81544. //# sourceMappingURL=babylon.edgesRenderer.js.map
  81545. var BABYLON;
  81546. (function (BABYLON) {
  81547. /**
  81548. * Special Glow Blur post process only blurring the alpha channel
  81549. * It enforces keeping the most luminous color in the color channel.
  81550. */
  81551. var GlowBlurPostProcess = /** @class */ (function (_super) {
  81552. __extends(GlowBlurPostProcess, _super);
  81553. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  81554. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  81555. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  81556. _this.direction = direction;
  81557. _this.kernel = kernel;
  81558. _this.onApplyObservable.add(function (effect) {
  81559. effect.setFloat2("screenSize", _this.width, _this.height);
  81560. effect.setVector2("direction", _this.direction);
  81561. effect.setFloat("blurWidth", _this.kernel);
  81562. });
  81563. return _this;
  81564. }
  81565. return GlowBlurPostProcess;
  81566. }(BABYLON.PostProcess));
  81567. /**
  81568. * The highlight layer Helps adding a glow effect around a mesh.
  81569. *
  81570. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  81571. * glowy meshes to your scene.
  81572. *
  81573. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  81574. */
  81575. var HighlightLayer = /** @class */ (function () {
  81576. /**
  81577. * Instantiates a new highlight Layer and references it to the scene..
  81578. * @param name The name of the layer
  81579. * @param scene The scene to use the layer in
  81580. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  81581. */
  81582. function HighlightLayer(name, scene, options) {
  81583. this.name = name;
  81584. this._vertexBuffers = {};
  81585. this._mainTextureDesiredSize = { width: 0, height: 0 };
  81586. this._meshes = {};
  81587. this._maxSize = 0;
  81588. this._shouldRender = false;
  81589. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  81590. this._excludedMeshes = {};
  81591. /**
  81592. * Specifies whether or not the inner glow is ACTIVE in the layer.
  81593. */
  81594. this.innerGlow = true;
  81595. /**
  81596. * Specifies whether or not the outer glow is ACTIVE in the layer.
  81597. */
  81598. this.outerGlow = true;
  81599. /**
  81600. * Specifies wether the highlight layer is enabled or not.
  81601. */
  81602. this.isEnabled = true;
  81603. /**
  81604. * An event triggered when the highlight layer has been disposed.
  81605. * @type {BABYLON.Observable}
  81606. */
  81607. this.onDisposeObservable = new BABYLON.Observable();
  81608. /**
  81609. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  81610. * @type {BABYLON.Observable}
  81611. */
  81612. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  81613. /**
  81614. * An event triggered when the highlight layer is being blurred.
  81615. * @type {BABYLON.Observable}
  81616. */
  81617. this.onBeforeBlurObservable = new BABYLON.Observable();
  81618. /**
  81619. * An event triggered when the highlight layer has been blurred.
  81620. * @type {BABYLON.Observable}
  81621. */
  81622. this.onAfterBlurObservable = new BABYLON.Observable();
  81623. /**
  81624. * An event triggered when the glowing blurred texture is being merged in the scene.
  81625. * @type {BABYLON.Observable}
  81626. */
  81627. this.onBeforeComposeObservable = new BABYLON.Observable();
  81628. /**
  81629. * An event triggered when the glowing blurred texture has been merged in the scene.
  81630. * @type {BABYLON.Observable}
  81631. */
  81632. this.onAfterComposeObservable = new BABYLON.Observable();
  81633. /**
  81634. * An event triggered when the highlight layer changes its size.
  81635. * @type {BABYLON.Observable}
  81636. */
  81637. this.onSizeChangedObservable = new BABYLON.Observable();
  81638. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81639. var engine = scene.getEngine();
  81640. this._engine = engine;
  81641. this._maxSize = this._engine.getCaps().maxTextureSize;
  81642. this._scene.highlightLayers.push(this);
  81643. // Warn on stencil.
  81644. if (!this._engine.isStencilEnable) {
  81645. 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 }");
  81646. }
  81647. // Adapt options
  81648. this._options = options || {
  81649. mainTextureRatio: 0.5,
  81650. blurTextureSizeRatio: 0.5,
  81651. blurHorizontalSize: 1.0,
  81652. blurVerticalSize: 1.0,
  81653. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  81654. camera: null
  81655. };
  81656. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  81657. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  81658. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  81659. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  81660. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  81661. // VBO
  81662. var vertices = [];
  81663. vertices.push(1, 1);
  81664. vertices.push(-1, 1);
  81665. vertices.push(-1, -1);
  81666. vertices.push(1, -1);
  81667. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81668. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  81669. this._createIndexBuffer();
  81670. // Effect
  81671. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  81672. // Render target
  81673. this.setMainTextureSize();
  81674. // Create Textures and post processes
  81675. this.createTextureAndPostProcesses();
  81676. }
  81677. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  81678. /**
  81679. * Gets the horizontal size of the blur.
  81680. */
  81681. get: function () {
  81682. return this._horizontalBlurPostprocess.kernel;
  81683. },
  81684. /**
  81685. * Specifies the horizontal size of the blur.
  81686. */
  81687. set: function (value) {
  81688. this._horizontalBlurPostprocess.kernel = value;
  81689. },
  81690. enumerable: true,
  81691. configurable: true
  81692. });
  81693. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  81694. /**
  81695. * Gets the vertical size of the blur.
  81696. */
  81697. get: function () {
  81698. return this._verticalBlurPostprocess.kernel;
  81699. },
  81700. /**
  81701. * Specifies the vertical size of the blur.
  81702. */
  81703. set: function (value) {
  81704. this._verticalBlurPostprocess.kernel = value;
  81705. },
  81706. enumerable: true,
  81707. configurable: true
  81708. });
  81709. Object.defineProperty(HighlightLayer.prototype, "camera", {
  81710. /**
  81711. * Gets the camera attached to the layer.
  81712. */
  81713. get: function () {
  81714. return this._options.camera;
  81715. },
  81716. enumerable: true,
  81717. configurable: true
  81718. });
  81719. HighlightLayer.prototype._createIndexBuffer = function () {
  81720. var engine = this._scene.getEngine();
  81721. // Indices
  81722. var indices = [];
  81723. indices.push(0);
  81724. indices.push(1);
  81725. indices.push(2);
  81726. indices.push(0);
  81727. indices.push(2);
  81728. indices.push(3);
  81729. this._indexBuffer = engine.createIndexBuffer(indices);
  81730. };
  81731. HighlightLayer.prototype._rebuild = function () {
  81732. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81733. if (vb) {
  81734. vb._rebuild();
  81735. }
  81736. this._createIndexBuffer();
  81737. };
  81738. /**
  81739. * Creates the render target textures and post processes used in the highlight layer.
  81740. */
  81741. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  81742. var _this = this;
  81743. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  81744. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  81745. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  81746. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  81747. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  81748. width: this._mainTextureDesiredSize.width,
  81749. height: this._mainTextureDesiredSize.height
  81750. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  81751. this._mainTexture.activeCamera = this._options.camera;
  81752. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81753. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81754. this._mainTexture.anisotropicFilteringLevel = 1;
  81755. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  81756. this._mainTexture.renderParticles = false;
  81757. this._mainTexture.renderList = null;
  81758. this._mainTexture.ignoreCameraViewport = true;
  81759. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  81760. width: blurTextureWidth,
  81761. height: blurTextureHeight
  81762. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  81763. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81764. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81765. this._blurTexture.anisotropicFilteringLevel = 16;
  81766. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  81767. this._blurTexture.renderParticles = false;
  81768. this._blurTexture.ignoreCameraViewport = true;
  81769. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  81770. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  81771. effect.setTexture("textureSampler", _this._mainTexture);
  81772. });
  81773. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  81774. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  81775. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  81776. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  81777. });
  81778. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  81779. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  81780. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  81781. });
  81782. }
  81783. else {
  81784. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  81785. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  81786. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  81787. });
  81788. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  81789. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  81790. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  81791. });
  81792. }
  81793. this._mainTexture.onAfterUnbindObservable.add(function () {
  81794. _this.onBeforeBlurObservable.notifyObservers(_this);
  81795. var internalTexture = _this._blurTexture.getInternalTexture();
  81796. if (internalTexture) {
  81797. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  81798. }
  81799. _this.onAfterBlurObservable.notifyObservers(_this);
  81800. });
  81801. // Custom render function
  81802. var renderSubMesh = function (subMesh) {
  81803. if (!_this._meshes) {
  81804. return;
  81805. }
  81806. var material = subMesh.getMaterial();
  81807. var mesh = subMesh.getRenderingMesh();
  81808. var scene = _this._scene;
  81809. var engine = scene.getEngine();
  81810. if (!material) {
  81811. return;
  81812. }
  81813. // Do not block in blend mode.
  81814. if (material.needAlphaBlendingForMesh(mesh)) {
  81815. return;
  81816. }
  81817. // Culling
  81818. engine.setState(material.backFaceCulling);
  81819. // Managing instances
  81820. var batch = mesh._getInstancesRenderList(subMesh._id);
  81821. if (batch.mustReturn) {
  81822. return;
  81823. }
  81824. // Excluded Mesh
  81825. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  81826. return;
  81827. }
  81828. ;
  81829. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  81830. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  81831. var emissiveTexture = null;
  81832. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  81833. emissiveTexture = material.emissiveTexture;
  81834. }
  81835. if (_this._isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  81836. engine.enableEffect(_this._glowMapGenerationEffect);
  81837. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  81838. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  81839. if (highlightLayerMesh) {
  81840. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  81841. }
  81842. else {
  81843. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  81844. }
  81845. // Alpha test
  81846. if (material && material.needAlphaTesting()) {
  81847. var alphaTexture = material.getAlphaTestTexture();
  81848. if (alphaTexture) {
  81849. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  81850. var textureMatrix = alphaTexture.getTextureMatrix();
  81851. if (textureMatrix) {
  81852. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  81853. }
  81854. }
  81855. }
  81856. // Glow emissive only
  81857. if (emissiveTexture) {
  81858. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  81859. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  81860. }
  81861. // Bones
  81862. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  81863. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  81864. }
  81865. // Draw
  81866. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  81867. }
  81868. else {
  81869. // Need to reset refresh rate of the shadowMap
  81870. _this._mainTexture.resetRefreshCounter();
  81871. }
  81872. };
  81873. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  81874. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  81875. var index;
  81876. var engine = _this._scene.getEngine();
  81877. if (depthOnlySubMeshes.length) {
  81878. engine.setColorWrite(false);
  81879. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  81880. renderSubMesh(depthOnlySubMeshes.data[index]);
  81881. }
  81882. engine.setColorWrite(true);
  81883. }
  81884. for (index = 0; index < opaqueSubMeshes.length; index++) {
  81885. renderSubMesh(opaqueSubMeshes.data[index]);
  81886. }
  81887. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  81888. renderSubMesh(alphaTestSubMeshes.data[index]);
  81889. }
  81890. for (index = 0; index < transparentSubMeshes.length; index++) {
  81891. renderSubMesh(transparentSubMeshes.data[index]);
  81892. }
  81893. };
  81894. this._mainTexture.onClearObservable.add(function (engine) {
  81895. engine.clear(HighlightLayer.neutralColor, true, true, true);
  81896. });
  81897. };
  81898. /**
  81899. * Checks for the readiness of the element composing the layer.
  81900. * @param subMesh the mesh to check for
  81901. * @param useInstances specify wether or not to use instances to render the mesh
  81902. * @param emissiveTexture the associated emissive texture used to generate the glow
  81903. * @return true if ready otherwise, false
  81904. */
  81905. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  81906. var material = subMesh.getMaterial();
  81907. var mesh = subMesh.getRenderingMesh();
  81908. if (!material || !mesh || !this._meshes) {
  81909. return false;
  81910. }
  81911. var emissiveTexture = null;
  81912. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  81913. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  81914. emissiveTexture = material.emissiveTexture;
  81915. }
  81916. return this._isReady(subMesh, useInstances, emissiveTexture);
  81917. };
  81918. /**
  81919. * Checks for the readiness of the element composing the layer.
  81920. * @param subMesh the mesh to check for
  81921. * @param useInstances specify wether or not to use instances to render the mesh
  81922. * @param emissiveTexture the associated emissive texture used to generate the glow
  81923. * @return true if ready otherwise, false
  81924. */
  81925. HighlightLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  81926. var material = subMesh.getMaterial();
  81927. if (!material) {
  81928. return false;
  81929. }
  81930. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  81931. return false;
  81932. }
  81933. var defines = [];
  81934. var attribs = [BABYLON.VertexBuffer.PositionKind];
  81935. var mesh = subMesh.getMesh();
  81936. var uv1 = false;
  81937. var uv2 = false;
  81938. // Alpha test
  81939. if (material && material.needAlphaTesting()) {
  81940. var alphaTexture = material.getAlphaTestTexture();
  81941. if (alphaTexture) {
  81942. defines.push("#define ALPHATEST");
  81943. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  81944. alphaTexture.coordinatesIndex === 1) {
  81945. defines.push("#define DIFFUSEUV2");
  81946. uv2 = true;
  81947. }
  81948. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  81949. defines.push("#define DIFFUSEUV1");
  81950. uv1 = true;
  81951. }
  81952. }
  81953. }
  81954. // Emissive
  81955. if (emissiveTexture) {
  81956. defines.push("#define EMISSIVE");
  81957. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  81958. emissiveTexture.coordinatesIndex === 1) {
  81959. defines.push("#define EMISSIVEUV2");
  81960. uv2 = true;
  81961. }
  81962. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  81963. defines.push("#define EMISSIVEUV1");
  81964. uv1 = true;
  81965. }
  81966. }
  81967. if (uv1) {
  81968. attribs.push(BABYLON.VertexBuffer.UVKind);
  81969. defines.push("#define UV1");
  81970. }
  81971. if (uv2) {
  81972. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  81973. defines.push("#define UV2");
  81974. }
  81975. // Bones
  81976. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  81977. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  81978. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  81979. if (mesh.numBoneInfluencers > 4) {
  81980. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  81981. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  81982. }
  81983. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  81984. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  81985. }
  81986. else {
  81987. defines.push("#define NUM_BONE_INFLUENCERS 0");
  81988. }
  81989. // Instances
  81990. if (useInstances) {
  81991. defines.push("#define INSTANCES");
  81992. attribs.push("world0");
  81993. attribs.push("world1");
  81994. attribs.push("world2");
  81995. attribs.push("world3");
  81996. }
  81997. // Get correct effect
  81998. var join = defines.join("\n");
  81999. if (this._cachedDefines !== join) {
  82000. this._cachedDefines = join;
  82001. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  82002. }
  82003. return this._glowMapGenerationEffect.isReady();
  82004. };
  82005. /**
  82006. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  82007. */
  82008. HighlightLayer.prototype.render = function () {
  82009. var currentEffect = this._glowMapMergeEffect;
  82010. // Check
  82011. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  82012. return;
  82013. var engine = this._scene.getEngine();
  82014. this.onBeforeComposeObservable.notifyObservers(this);
  82015. // Render
  82016. engine.enableEffect(currentEffect);
  82017. engine.setState(false);
  82018. // Cache
  82019. var previousStencilBuffer = engine.getStencilBuffer();
  82020. var previousStencilFunction = engine.getStencilFunction();
  82021. var previousStencilMask = engine.getStencilMask();
  82022. var previousStencilOperationPass = engine.getStencilOperationPass();
  82023. var previousStencilOperationFail = engine.getStencilOperationFail();
  82024. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  82025. var previousAlphaMode = engine.getAlphaMode();
  82026. // Texture
  82027. currentEffect.setTexture("textureSampler", this._blurTexture);
  82028. // VBOs
  82029. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  82030. // Stencil operations
  82031. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  82032. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  82033. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  82034. // Draw order
  82035. engine.setAlphaMode(this._options.alphaBlendingMode);
  82036. engine.setStencilMask(0x00);
  82037. engine.setStencilBuffer(true);
  82038. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  82039. if (this.outerGlow) {
  82040. currentEffect.setFloat("offset", 0);
  82041. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  82042. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82043. }
  82044. if (this.innerGlow) {
  82045. currentEffect.setFloat("offset", 1);
  82046. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  82047. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82048. }
  82049. // Restore Cache
  82050. engine.setStencilFunction(previousStencilFunction);
  82051. engine.setStencilMask(previousStencilMask);
  82052. engine.setAlphaMode(previousAlphaMode);
  82053. engine.setStencilBuffer(previousStencilBuffer);
  82054. engine.setStencilOperationPass(previousStencilOperationPass);
  82055. engine.setStencilOperationFail(previousStencilOperationFail);
  82056. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  82057. engine._stencilState.reset();
  82058. this.onAfterComposeObservable.notifyObservers(this);
  82059. // Handle size changes.
  82060. var size = this._mainTexture.getSize();
  82061. this.setMainTextureSize();
  82062. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  82063. // Recreate RTT and post processes on size change.
  82064. this.onSizeChangedObservable.notifyObservers(this);
  82065. this.disposeTextureAndPostProcesses();
  82066. this.createTextureAndPostProcesses();
  82067. }
  82068. };
  82069. /**
  82070. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  82071. * @param mesh The mesh to exclude from the highlight layer
  82072. */
  82073. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  82074. if (!this._excludedMeshes) {
  82075. return;
  82076. }
  82077. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  82078. if (!meshExcluded) {
  82079. this._excludedMeshes[mesh.uniqueId] = {
  82080. mesh: mesh,
  82081. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  82082. mesh.getEngine().setStencilBuffer(false);
  82083. }),
  82084. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  82085. mesh.getEngine().setStencilBuffer(true);
  82086. }),
  82087. };
  82088. }
  82089. };
  82090. /**
  82091. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  82092. * @param mesh The mesh to highlight
  82093. */
  82094. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  82095. if (!this._excludedMeshes) {
  82096. return;
  82097. }
  82098. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  82099. if (meshExcluded) {
  82100. if (meshExcluded.beforeRender) {
  82101. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  82102. }
  82103. if (meshExcluded.afterRender) {
  82104. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  82105. }
  82106. }
  82107. this._excludedMeshes[mesh.uniqueId] = null;
  82108. };
  82109. /**
  82110. * Determine if a given mesh will be highlighted by the current HighlightLayer
  82111. * @param mesh mesh to test
  82112. * @returns true if the mesh will be highlighted by the current HighlightLayer
  82113. */
  82114. HighlightLayer.prototype.hasMesh = function (mesh) {
  82115. if (!this._meshes) {
  82116. return false;
  82117. }
  82118. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  82119. };
  82120. /**
  82121. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  82122. * @param mesh The mesh to highlight
  82123. * @param color The color of the highlight
  82124. * @param glowEmissiveOnly Extract the glow from the emissive texture
  82125. */
  82126. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  82127. var _this = this;
  82128. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  82129. if (!this._meshes) {
  82130. return;
  82131. }
  82132. var meshHighlight = this._meshes[mesh.uniqueId];
  82133. if (meshHighlight) {
  82134. meshHighlight.color = color;
  82135. }
  82136. else {
  82137. this._meshes[mesh.uniqueId] = {
  82138. mesh: mesh,
  82139. color: color,
  82140. // Lambda required for capture due to Observable this context
  82141. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  82142. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  82143. _this.defaultStencilReference(mesh);
  82144. }
  82145. else {
  82146. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  82147. }
  82148. }),
  82149. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  82150. glowEmissiveOnly: glowEmissiveOnly
  82151. };
  82152. }
  82153. this._shouldRender = true;
  82154. };
  82155. /**
  82156. * Remove a mesh from the highlight layer in order to make it stop glowing.
  82157. * @param mesh The mesh to highlight
  82158. */
  82159. HighlightLayer.prototype.removeMesh = function (mesh) {
  82160. if (!this._meshes) {
  82161. return;
  82162. }
  82163. var meshHighlight = this._meshes[mesh.uniqueId];
  82164. if (meshHighlight) {
  82165. if (meshHighlight.observerHighlight) {
  82166. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  82167. }
  82168. if (meshHighlight.observerDefault) {
  82169. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  82170. }
  82171. delete this._meshes[mesh.uniqueId];
  82172. }
  82173. this._shouldRender = false;
  82174. for (var meshHighlightToCheck in this._meshes) {
  82175. if (this._meshes[meshHighlightToCheck]) {
  82176. this._shouldRender = true;
  82177. break;
  82178. }
  82179. }
  82180. };
  82181. /**
  82182. * Returns true if the layer contains information to display, otherwise false.
  82183. */
  82184. HighlightLayer.prototype.shouldRender = function () {
  82185. return this.isEnabled && this._shouldRender;
  82186. };
  82187. /**
  82188. * Sets the main texture desired size which is the closest power of two
  82189. * of the engine canvas size.
  82190. */
  82191. HighlightLayer.prototype.setMainTextureSize = function () {
  82192. if (this._options.mainTextureFixedSize) {
  82193. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  82194. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  82195. }
  82196. else {
  82197. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  82198. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  82199. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  82200. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  82201. }
  82202. };
  82203. /**
  82204. * Force the stencil to the normal expected value for none glowing parts
  82205. */
  82206. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  82207. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  82208. };
  82209. /**
  82210. * Dispose only the render target textures and post process.
  82211. */
  82212. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  82213. this._blurTexture.dispose();
  82214. this._mainTexture.dispose();
  82215. this._downSamplePostprocess.dispose();
  82216. this._horizontalBlurPostprocess.dispose();
  82217. this._verticalBlurPostprocess.dispose();
  82218. };
  82219. /**
  82220. * Dispose the highlight layer and free resources.
  82221. */
  82222. HighlightLayer.prototype.dispose = function () {
  82223. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82224. if (vertexBuffer) {
  82225. vertexBuffer.dispose();
  82226. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82227. }
  82228. if (this._indexBuffer) {
  82229. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82230. this._indexBuffer = null;
  82231. }
  82232. // Clean textures and post processes
  82233. this.disposeTextureAndPostProcesses();
  82234. if (this._meshes) {
  82235. // Clean mesh references
  82236. for (var id in this._meshes) {
  82237. var meshHighlight = this._meshes[id];
  82238. if (meshHighlight && meshHighlight.mesh) {
  82239. if (meshHighlight.observerHighlight) {
  82240. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  82241. }
  82242. if (meshHighlight.observerDefault) {
  82243. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  82244. }
  82245. }
  82246. }
  82247. this._meshes = null;
  82248. }
  82249. if (this._excludedMeshes) {
  82250. for (var id in this._excludedMeshes) {
  82251. var meshHighlight = this._excludedMeshes[id];
  82252. if (meshHighlight) {
  82253. if (meshHighlight.beforeRender) {
  82254. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  82255. }
  82256. if (meshHighlight.afterRender) {
  82257. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  82258. }
  82259. }
  82260. }
  82261. this._excludedMeshes = null;
  82262. }
  82263. // Remove from scene
  82264. var index = this._scene.highlightLayers.indexOf(this, 0);
  82265. if (index > -1) {
  82266. this._scene.highlightLayers.splice(index, 1);
  82267. }
  82268. // Callback
  82269. this.onDisposeObservable.notifyObservers(this);
  82270. this.onDisposeObservable.clear();
  82271. this.onBeforeRenderMainTextureObservable.clear();
  82272. this.onBeforeBlurObservable.clear();
  82273. this.onBeforeComposeObservable.clear();
  82274. this.onAfterComposeObservable.clear();
  82275. this.onSizeChangedObservable.clear();
  82276. };
  82277. /**
  82278. * The neutral color used during the preparation of the glow effect.
  82279. * This is black by default as the blend operation is a blend operation.
  82280. */
  82281. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  82282. /**
  82283. * Stencil value used for glowing meshes.
  82284. */
  82285. HighlightLayer.glowingMeshStencilReference = 0x02;
  82286. /**
  82287. * Stencil value used for the other meshes in the scene.
  82288. */
  82289. HighlightLayer.normalMeshStencilReference = 0x01;
  82290. return HighlightLayer;
  82291. }());
  82292. BABYLON.HighlightLayer = HighlightLayer;
  82293. })(BABYLON || (BABYLON = {}));
  82294. //# sourceMappingURL=babylon.highlightlayer.js.map
  82295. var BABYLON;
  82296. (function (BABYLON) {
  82297. /**
  82298. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  82299. */
  82300. var AssetTaskState;
  82301. (function (AssetTaskState) {
  82302. /**
  82303. * Initialization
  82304. */
  82305. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  82306. /**
  82307. * Running
  82308. */
  82309. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  82310. /**
  82311. * Done
  82312. */
  82313. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  82314. /**
  82315. * Error
  82316. */
  82317. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  82318. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  82319. /**
  82320. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  82321. */
  82322. var AbstractAssetTask = /** @class */ (function () {
  82323. /**
  82324. * Creates a new {BABYLON.AssetsManager}
  82325. * @param name defines the name of the task
  82326. */
  82327. function AbstractAssetTask(
  82328. /**
  82329. * Task name
  82330. */ name) {
  82331. this.name = name;
  82332. this._isCompleted = false;
  82333. this._taskState = AssetTaskState.INIT;
  82334. }
  82335. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  82336. /**
  82337. * Get if the task is completed
  82338. */
  82339. get: function () {
  82340. return this._isCompleted;
  82341. },
  82342. enumerable: true,
  82343. configurable: true
  82344. });
  82345. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  82346. /**
  82347. * Gets the current state of the task
  82348. */
  82349. get: function () {
  82350. return this._taskState;
  82351. },
  82352. enumerable: true,
  82353. configurable: true
  82354. });
  82355. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  82356. /**
  82357. * Gets the current error object (if task is in error)
  82358. */
  82359. get: function () {
  82360. return this._errorObject;
  82361. },
  82362. enumerable: true,
  82363. configurable: true
  82364. });
  82365. /**
  82366. * Internal only
  82367. * @ignore
  82368. */
  82369. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  82370. if (this._errorObject) {
  82371. return;
  82372. }
  82373. this._errorObject = {
  82374. message: message,
  82375. exception: exception
  82376. };
  82377. };
  82378. /**
  82379. * Execute the current task
  82380. * @param scene defines the scene where you want your assets to be loaded
  82381. * @param onSuccess is a callback called when the task is successfully executed
  82382. * @param onError is a callback called if an error occurs
  82383. */
  82384. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  82385. var _this = this;
  82386. this._taskState = AssetTaskState.RUNNING;
  82387. this.runTask(scene, function () {
  82388. _this.onDoneCallback(onSuccess, onError);
  82389. }, function (msg, exception) {
  82390. _this.onErrorCallback(onError, msg, exception);
  82391. });
  82392. };
  82393. /**
  82394. * Execute the current task
  82395. * @param scene defines the scene where you want your assets to be loaded
  82396. * @param onSuccess is a callback called when the task is successfully executed
  82397. * @param onError is a callback called if an error occurs
  82398. */
  82399. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  82400. throw new Error("runTask is not implemented");
  82401. };
  82402. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  82403. this._taskState = AssetTaskState.ERROR;
  82404. this._errorObject = {
  82405. message: message,
  82406. exception: exception
  82407. };
  82408. if (this.onError) {
  82409. this.onError(this, message, exception);
  82410. }
  82411. onError();
  82412. };
  82413. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  82414. try {
  82415. this._taskState = AssetTaskState.DONE;
  82416. this._isCompleted = true;
  82417. if (this.onSuccess) {
  82418. this.onSuccess(this);
  82419. }
  82420. onSuccess();
  82421. }
  82422. catch (e) {
  82423. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  82424. }
  82425. };
  82426. return AbstractAssetTask;
  82427. }());
  82428. BABYLON.AbstractAssetTask = AbstractAssetTask;
  82429. /**
  82430. * Class used to share progress information about assets loading
  82431. */
  82432. var AssetsProgressEvent = /** @class */ (function () {
  82433. /**
  82434. * Creates a {BABYLON.AssetsProgressEvent}
  82435. * @param remainingCount defines the number of remaining tasks to process
  82436. * @param totalCount defines the total number of tasks
  82437. * @param task defines the task that was just processed
  82438. */
  82439. function AssetsProgressEvent(remainingCount, totalCount, task) {
  82440. this.remainingCount = remainingCount;
  82441. this.totalCount = totalCount;
  82442. this.task = task;
  82443. }
  82444. return AssetsProgressEvent;
  82445. }());
  82446. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  82447. /**
  82448. * Define a task used by {BABYLON.AssetsManager} to load meshes
  82449. */
  82450. var MeshAssetTask = /** @class */ (function (_super) {
  82451. __extends(MeshAssetTask, _super);
  82452. /**
  82453. * Creates a new {BABYLON.MeshAssetTask}
  82454. * @param name defines the name of the task
  82455. * @param meshesNames defines the list of mesh's names you want to load
  82456. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  82457. * @param sceneFilename defines the filename of the scene to load from
  82458. */
  82459. function MeshAssetTask(
  82460. /**
  82461. * Defines the name of the task
  82462. */
  82463. name,
  82464. /**
  82465. * Defines the list of mesh's names you want to load
  82466. */
  82467. meshesNames,
  82468. /**
  82469. * Defines the root url to use as a base to load your meshes and associated resources
  82470. */
  82471. rootUrl,
  82472. /**
  82473. * Defines the filename of the scene to load from
  82474. */
  82475. sceneFilename) {
  82476. var _this = _super.call(this, name) || this;
  82477. _this.name = name;
  82478. _this.meshesNames = meshesNames;
  82479. _this.rootUrl = rootUrl;
  82480. _this.sceneFilename = sceneFilename;
  82481. return _this;
  82482. }
  82483. /**
  82484. * Execute the current task
  82485. * @param scene defines the scene where you want your assets to be loaded
  82486. * @param onSuccess is a callback called when the task is successfully executed
  82487. * @param onError is a callback called if an error occurs
  82488. */
  82489. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  82490. var _this = this;
  82491. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  82492. _this.loadedMeshes = meshes;
  82493. _this.loadedParticleSystems = particleSystems;
  82494. _this.loadedSkeletons = skeletons;
  82495. onSuccess();
  82496. }, null, function (scene, message, exception) {
  82497. onError(message, exception);
  82498. });
  82499. };
  82500. return MeshAssetTask;
  82501. }(AbstractAssetTask));
  82502. BABYLON.MeshAssetTask = MeshAssetTask;
  82503. /**
  82504. * Define a task used by {BABYLON.AssetsManager} to load text content
  82505. */
  82506. var TextFileAssetTask = /** @class */ (function (_super) {
  82507. __extends(TextFileAssetTask, _super);
  82508. /**
  82509. * Creates a new TextFileAssetTask object
  82510. * @param name defines the name of the task
  82511. * @param url defines the location of the file to load
  82512. */
  82513. function TextFileAssetTask(
  82514. /**
  82515. * Defines the name of the task
  82516. */
  82517. name,
  82518. /**
  82519. * Defines the location of the file to load
  82520. */
  82521. url) {
  82522. var _this = _super.call(this, name) || this;
  82523. _this.name = name;
  82524. _this.url = url;
  82525. return _this;
  82526. }
  82527. /**
  82528. * Execute the current task
  82529. * @param scene defines the scene where you want your assets to be loaded
  82530. * @param onSuccess is a callback called when the task is successfully executed
  82531. * @param onError is a callback called if an error occurs
  82532. */
  82533. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  82534. var _this = this;
  82535. scene._loadFile(this.url, function (data) {
  82536. _this.text = data;
  82537. onSuccess();
  82538. }, undefined, false, true, function (request, exception) {
  82539. if (request) {
  82540. onError(request.status + " " + request.statusText, exception);
  82541. }
  82542. });
  82543. };
  82544. return TextFileAssetTask;
  82545. }(AbstractAssetTask));
  82546. BABYLON.TextFileAssetTask = TextFileAssetTask;
  82547. /**
  82548. * Define a task used by {BABYLON.AssetsManager} to load binary data
  82549. */
  82550. var BinaryFileAssetTask = /** @class */ (function (_super) {
  82551. __extends(BinaryFileAssetTask, _super);
  82552. /**
  82553. * Creates a new BinaryFileAssetTask object
  82554. * @param name defines the name of the new task
  82555. * @param url defines the location of the file to load
  82556. */
  82557. function BinaryFileAssetTask(
  82558. /**
  82559. * Defines the name of the task
  82560. */
  82561. name,
  82562. /**
  82563. * Defines the location of the file to load
  82564. */
  82565. url) {
  82566. var _this = _super.call(this, name) || this;
  82567. _this.name = name;
  82568. _this.url = url;
  82569. return _this;
  82570. }
  82571. /**
  82572. * Execute the current task
  82573. * @param scene defines the scene where you want your assets to be loaded
  82574. * @param onSuccess is a callback called when the task is successfully executed
  82575. * @param onError is a callback called if an error occurs
  82576. */
  82577. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  82578. var _this = this;
  82579. scene._loadFile(this.url, function (data) {
  82580. _this.data = data;
  82581. onSuccess();
  82582. }, undefined, true, true, function (request, exception) {
  82583. if (request) {
  82584. onError(request.status + " " + request.statusText, exception);
  82585. }
  82586. });
  82587. };
  82588. return BinaryFileAssetTask;
  82589. }(AbstractAssetTask));
  82590. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  82591. /**
  82592. * Define a task used by {BABYLON.AssetsManager} to load images
  82593. */
  82594. var ImageAssetTask = /** @class */ (function (_super) {
  82595. __extends(ImageAssetTask, _super);
  82596. /**
  82597. * Creates a new ImageAssetTask
  82598. * @param name defines the name of the task
  82599. * @param url defines the location of the image to load
  82600. */
  82601. function ImageAssetTask(
  82602. /**
  82603. * Defines the name of the task
  82604. */
  82605. name,
  82606. /**
  82607. * Defines the location of the image to load
  82608. */
  82609. url) {
  82610. var _this = _super.call(this, name) || this;
  82611. _this.name = name;
  82612. _this.url = url;
  82613. return _this;
  82614. }
  82615. /**
  82616. * Execute the current task
  82617. * @param scene defines the scene where you want your assets to be loaded
  82618. * @param onSuccess is a callback called when the task is successfully executed
  82619. * @param onError is a callback called if an error occurs
  82620. */
  82621. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  82622. var _this = this;
  82623. var img = new Image();
  82624. BABYLON.Tools.SetCorsBehavior(this.url, img);
  82625. img.onload = function () {
  82626. _this.image = img;
  82627. onSuccess();
  82628. };
  82629. img.onerror = function (err) {
  82630. onError("Error loading image", err);
  82631. };
  82632. img.src = this.url;
  82633. };
  82634. return ImageAssetTask;
  82635. }(AbstractAssetTask));
  82636. BABYLON.ImageAssetTask = ImageAssetTask;
  82637. /**
  82638. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  82639. */
  82640. var TextureAssetTask = /** @class */ (function (_super) {
  82641. __extends(TextureAssetTask, _super);
  82642. /**
  82643. * Creates a new TextureAssetTask object
  82644. * @param name defines the name of the task
  82645. * @param url defines the location of the file to load
  82646. * @param noMipmap defines if mipmap should not be generated (default is false)
  82647. * @param invertY defines if texture must be inverted on Y axis (default is false)
  82648. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  82649. */
  82650. function TextureAssetTask(
  82651. /**
  82652. * Defines the name of the task
  82653. */
  82654. name,
  82655. /**
  82656. * Defines the location of the file to load
  82657. */
  82658. url,
  82659. /**
  82660. * Defines if mipmap should not be generated (default is false)
  82661. */
  82662. noMipmap,
  82663. /**
  82664. * Defines if texture must be inverted on Y axis (default is false)
  82665. */
  82666. invertY,
  82667. /**
  82668. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  82669. */
  82670. samplingMode) {
  82671. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  82672. var _this = _super.call(this, name) || this;
  82673. _this.name = name;
  82674. _this.url = url;
  82675. _this.noMipmap = noMipmap;
  82676. _this.invertY = invertY;
  82677. _this.samplingMode = samplingMode;
  82678. return _this;
  82679. }
  82680. /**
  82681. * Execute the current task
  82682. * @param scene defines the scene where you want your assets to be loaded
  82683. * @param onSuccess is a callback called when the task is successfully executed
  82684. * @param onError is a callback called if an error occurs
  82685. */
  82686. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  82687. var onload = function () {
  82688. onSuccess();
  82689. };
  82690. var onerror = function (message, exception) {
  82691. onError(message, exception);
  82692. };
  82693. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  82694. };
  82695. return TextureAssetTask;
  82696. }(AbstractAssetTask));
  82697. BABYLON.TextureAssetTask = TextureAssetTask;
  82698. /**
  82699. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  82700. */
  82701. var CubeTextureAssetTask = /** @class */ (function (_super) {
  82702. __extends(CubeTextureAssetTask, _super);
  82703. /**
  82704. * Creates a new CubeTextureAssetTask
  82705. * @param name defines the name of the task
  82706. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  82707. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  82708. * @param noMipmap defines if mipmaps should not be generated (default is false)
  82709. * @param files defines the explicit list of files (undefined by default)
  82710. */
  82711. function CubeTextureAssetTask(
  82712. /**
  82713. * Defines the name of the task
  82714. */
  82715. name,
  82716. /**
  82717. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  82718. */
  82719. url,
  82720. /**
  82721. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  82722. */
  82723. extensions,
  82724. /**
  82725. * Defines if mipmaps should not be generated (default is false)
  82726. */
  82727. noMipmap,
  82728. /**
  82729. * Defines the explicit list of files (undefined by default)
  82730. */
  82731. files) {
  82732. var _this = _super.call(this, name) || this;
  82733. _this.name = name;
  82734. _this.url = url;
  82735. _this.extensions = extensions;
  82736. _this.noMipmap = noMipmap;
  82737. _this.files = files;
  82738. return _this;
  82739. }
  82740. /**
  82741. * Execute the current task
  82742. * @param scene defines the scene where you want your assets to be loaded
  82743. * @param onSuccess is a callback called when the task is successfully executed
  82744. * @param onError is a callback called if an error occurs
  82745. */
  82746. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  82747. var onload = function () {
  82748. onSuccess();
  82749. };
  82750. var onerror = function (message, exception) {
  82751. onError(message, exception);
  82752. };
  82753. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  82754. };
  82755. return CubeTextureAssetTask;
  82756. }(AbstractAssetTask));
  82757. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  82758. /**
  82759. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  82760. */
  82761. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  82762. __extends(HDRCubeTextureAssetTask, _super);
  82763. /**
  82764. * Creates a new HDRCubeTextureAssetTask object
  82765. * @param name defines the name of the task
  82766. * @param url defines the location of the file to load
  82767. * @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.
  82768. * @param noMipmap defines if mipmaps should not be generated (default is false)
  82769. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  82770. * @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)
  82771. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  82772. */
  82773. function HDRCubeTextureAssetTask(
  82774. /**
  82775. * Defines the name of the task
  82776. */
  82777. name,
  82778. /**
  82779. * Defines the location of the file to load
  82780. */
  82781. url,
  82782. /**
  82783. * 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.
  82784. */
  82785. size,
  82786. /**
  82787. * Defines if mipmaps should not be generated (default is false)
  82788. */
  82789. noMipmap,
  82790. /**
  82791. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  82792. */
  82793. generateHarmonics,
  82794. /**
  82795. * 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)
  82796. */
  82797. useInGammaSpace,
  82798. /**
  82799. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  82800. */
  82801. usePMREMGenerator) {
  82802. if (noMipmap === void 0) { noMipmap = false; }
  82803. if (generateHarmonics === void 0) { generateHarmonics = true; }
  82804. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  82805. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  82806. var _this = _super.call(this, name) || this;
  82807. _this.name = name;
  82808. _this.url = url;
  82809. _this.size = size;
  82810. _this.noMipmap = noMipmap;
  82811. _this.generateHarmonics = generateHarmonics;
  82812. _this.useInGammaSpace = useInGammaSpace;
  82813. _this.usePMREMGenerator = usePMREMGenerator;
  82814. return _this;
  82815. }
  82816. /**
  82817. * Execute the current task
  82818. * @param scene defines the scene where you want your assets to be loaded
  82819. * @param onSuccess is a callback called when the task is successfully executed
  82820. * @param onError is a callback called if an error occurs
  82821. */
  82822. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  82823. var onload = function () {
  82824. onSuccess();
  82825. };
  82826. var onerror = function (message, exception) {
  82827. onError(message, exception);
  82828. };
  82829. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  82830. };
  82831. return HDRCubeTextureAssetTask;
  82832. }(AbstractAssetTask));
  82833. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  82834. /**
  82835. * This class can be used to easily import assets into a scene
  82836. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  82837. */
  82838. var AssetsManager = /** @class */ (function () {
  82839. /**
  82840. * Creates a new AssetsManager
  82841. * @param scene defines the scene to work on
  82842. */
  82843. function AssetsManager(scene) {
  82844. this._isLoading = false;
  82845. this._tasks = new Array();
  82846. this._waitingTasksCount = 0;
  82847. this._totalTasksCount = 0;
  82848. /**
  82849. * Observable called when all tasks are processed
  82850. */
  82851. this.onTaskSuccessObservable = new BABYLON.Observable();
  82852. /**
  82853. * Observable called when a task had an error
  82854. */
  82855. this.onTaskErrorObservable = new BABYLON.Observable();
  82856. /**
  82857. * Observable called when a task is successful
  82858. */
  82859. this.onTasksDoneObservable = new BABYLON.Observable();
  82860. /**
  82861. * Observable called when a task is done (whatever the result is)
  82862. */
  82863. this.onProgressObservable = new BABYLON.Observable();
  82864. /**
  82865. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  82866. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  82867. */
  82868. this.useDefaultLoadingScreen = true;
  82869. this._scene = scene;
  82870. }
  82871. /**
  82872. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  82873. * @param taskName defines the name of the new task
  82874. * @param meshesNames defines the name of meshes to load
  82875. * @param rootUrl defines the root url to use to locate files
  82876. * @param sceneFilename defines the filename of the scene file
  82877. * @returns a new {BABYLON.MeshAssetTask} object
  82878. */
  82879. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  82880. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  82881. this._tasks.push(task);
  82882. return task;
  82883. };
  82884. /**
  82885. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  82886. * @param taskName defines the name of the new task
  82887. * @param url defines the url of the file to load
  82888. * @returns a new {BABYLON.TextFileAssetTask} object
  82889. */
  82890. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  82891. var task = new TextFileAssetTask(taskName, url);
  82892. this._tasks.push(task);
  82893. return task;
  82894. };
  82895. /**
  82896. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  82897. * @param taskName defines the name of the new task
  82898. * @param url defines the url of the file to load
  82899. * @returns a new {BABYLON.BinaryFileAssetTask} object
  82900. */
  82901. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  82902. var task = new BinaryFileAssetTask(taskName, url);
  82903. this._tasks.push(task);
  82904. return task;
  82905. };
  82906. /**
  82907. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  82908. * @param taskName defines the name of the new task
  82909. * @param url defines the url of the file to load
  82910. * @returns a new {BABYLON.ImageAssetTask} object
  82911. */
  82912. AssetsManager.prototype.addImageTask = function (taskName, url) {
  82913. var task = new ImageAssetTask(taskName, url);
  82914. this._tasks.push(task);
  82915. return task;
  82916. };
  82917. /**
  82918. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  82919. * @param taskName defines the name of the new task
  82920. * @param url defines the url of the file to load
  82921. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  82922. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  82923. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  82924. * @returns a new {BABYLON.TextureAssetTask} object
  82925. */
  82926. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  82927. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  82928. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  82929. this._tasks.push(task);
  82930. return task;
  82931. };
  82932. /**
  82933. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  82934. * @param taskName defines the name of the new task
  82935. * @param url defines the url of the file to load
  82936. * @param extensions defines the extension to use to load the cube map (can be null)
  82937. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  82938. * @param files defines the list of files to load (can be null)
  82939. * @returns a new {BABYLON.CubeTextureAssetTask} object
  82940. */
  82941. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  82942. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  82943. this._tasks.push(task);
  82944. return task;
  82945. };
  82946. /**
  82947. *
  82948. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  82949. * @param taskName defines the name of the new task
  82950. * @param url defines the url of the file to load
  82951. * @param size defines the size you want for the cubemap (can be null)
  82952. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  82953. * @param generateHarmonics defines if you want to automatically generate (true by default)
  82954. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  82955. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  82956. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  82957. */
  82958. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  82959. if (noMipmap === void 0) { noMipmap = false; }
  82960. if (generateHarmonics === void 0) { generateHarmonics = true; }
  82961. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  82962. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  82963. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  82964. this._tasks.push(task);
  82965. return task;
  82966. };
  82967. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  82968. var _this = this;
  82969. this._waitingTasksCount--;
  82970. try {
  82971. if (task.taskState === AssetTaskState.DONE) {
  82972. // Let's remove successfull tasks
  82973. BABYLON.Tools.SetImmediate(function () {
  82974. var index = _this._tasks.indexOf(task);
  82975. if (index > -1) {
  82976. _this._tasks.splice(index, 1);
  82977. }
  82978. });
  82979. }
  82980. if (this.onProgress) {
  82981. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  82982. }
  82983. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  82984. }
  82985. catch (e) {
  82986. BABYLON.Tools.Error("Error running progress callbacks.");
  82987. console.log(e);
  82988. }
  82989. if (this._waitingTasksCount === 0) {
  82990. try {
  82991. if (this.onFinish) {
  82992. this.onFinish(this._tasks);
  82993. }
  82994. this.onTasksDoneObservable.notifyObservers(this._tasks);
  82995. }
  82996. catch (e) {
  82997. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  82998. console.log(e);
  82999. }
  83000. this._isLoading = false;
  83001. this._scene.getEngine().hideLoadingUI();
  83002. }
  83003. };
  83004. AssetsManager.prototype._runTask = function (task) {
  83005. var _this = this;
  83006. var done = function () {
  83007. try {
  83008. if (_this.onTaskSuccess) {
  83009. _this.onTaskSuccess(task);
  83010. }
  83011. _this.onTaskSuccessObservable.notifyObservers(task);
  83012. _this._decreaseWaitingTasksCount(task);
  83013. }
  83014. catch (e) {
  83015. error("Error executing task success callbacks", e);
  83016. }
  83017. };
  83018. var error = function (message, exception) {
  83019. task._setErrorObject(message, exception);
  83020. if (_this.onTaskError) {
  83021. _this.onTaskError(task);
  83022. }
  83023. _this.onTaskErrorObservable.notifyObservers(task);
  83024. _this._decreaseWaitingTasksCount(task);
  83025. };
  83026. task.run(this._scene, done, error);
  83027. };
  83028. /**
  83029. * Reset the {BABYLON.AssetsManager} and remove all tasks
  83030. * @return the current instance of the {BABYLON.AssetsManager}
  83031. */
  83032. AssetsManager.prototype.reset = function () {
  83033. this._isLoading = false;
  83034. this._tasks = new Array();
  83035. return this;
  83036. };
  83037. /**
  83038. * Start the loading process
  83039. * @return the current instance of the {BABYLON.AssetsManager}
  83040. */
  83041. AssetsManager.prototype.load = function () {
  83042. if (this._isLoading) {
  83043. return this;
  83044. }
  83045. this._isLoading = true;
  83046. this._waitingTasksCount = this._tasks.length;
  83047. this._totalTasksCount = this._tasks.length;
  83048. if (this._waitingTasksCount === 0) {
  83049. if (this.onFinish) {
  83050. this.onFinish(this._tasks);
  83051. }
  83052. this.onTasksDoneObservable.notifyObservers(this._tasks);
  83053. return this;
  83054. }
  83055. if (this.useDefaultLoadingScreen) {
  83056. this._scene.getEngine().displayLoadingUI();
  83057. }
  83058. for (var index = 0; index < this._tasks.length; index++) {
  83059. var task = this._tasks[index];
  83060. this._runTask(task);
  83061. }
  83062. return this;
  83063. };
  83064. return AssetsManager;
  83065. }());
  83066. BABYLON.AssetsManager = AssetsManager;
  83067. })(BABYLON || (BABYLON = {}));
  83068. //# sourceMappingURL=babylon.assetsManager.js.map
  83069. var BABYLON;
  83070. (function (BABYLON) {
  83071. var serializedGeometries = [];
  83072. var serializeGeometry = function (geometry, serializationGeometries) {
  83073. if (serializedGeometries[geometry.id]) {
  83074. return;
  83075. }
  83076. if (geometry.doNotSerialize) {
  83077. return;
  83078. }
  83079. if (geometry instanceof BABYLON.BoxGeometry) {
  83080. serializationGeometries.boxes.push(geometry.serialize());
  83081. }
  83082. else if (geometry instanceof BABYLON.SphereGeometry) {
  83083. serializationGeometries.spheres.push(geometry.serialize());
  83084. }
  83085. else if (geometry instanceof BABYLON.CylinderGeometry) {
  83086. serializationGeometries.cylinders.push(geometry.serialize());
  83087. }
  83088. else if (geometry instanceof BABYLON.TorusGeometry) {
  83089. serializationGeometries.toruses.push(geometry.serialize());
  83090. }
  83091. else if (geometry instanceof BABYLON.GroundGeometry) {
  83092. serializationGeometries.grounds.push(geometry.serialize());
  83093. }
  83094. else if (geometry instanceof BABYLON.Plane) {
  83095. serializationGeometries.planes.push(geometry.serialize());
  83096. }
  83097. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  83098. serializationGeometries.torusKnots.push(geometry.serialize());
  83099. }
  83100. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  83101. throw new Error("Unknown primitive type");
  83102. }
  83103. else {
  83104. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  83105. }
  83106. serializedGeometries[geometry.id] = true;
  83107. };
  83108. var serializeMesh = function (mesh, serializationScene) {
  83109. var serializationObject = {};
  83110. // Geometry
  83111. var geometry = mesh._geometry;
  83112. if (geometry) {
  83113. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  83114. // 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
  83115. serializeGeometry(geometry, serializationScene.geometries);
  83116. }
  83117. }
  83118. // Custom
  83119. if (mesh.serialize) {
  83120. mesh.serialize(serializationObject);
  83121. }
  83122. return serializationObject;
  83123. };
  83124. var finalizeSingleMesh = function (mesh, serializationObject) {
  83125. //only works if the mesh is already loaded
  83126. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  83127. //serialize material
  83128. if (mesh.material) {
  83129. if (mesh.material instanceof BABYLON.StandardMaterial) {
  83130. serializationObject.materials = serializationObject.materials || [];
  83131. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  83132. serializationObject.materials.push(mesh.material.serialize());
  83133. }
  83134. }
  83135. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  83136. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  83137. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  83138. serializationObject.multiMaterials.push(mesh.material.serialize());
  83139. }
  83140. }
  83141. }
  83142. //serialize geometry
  83143. var geometry = mesh._geometry;
  83144. if (geometry) {
  83145. if (!serializationObject.geometries) {
  83146. serializationObject.geometries = {};
  83147. serializationObject.geometries.boxes = [];
  83148. serializationObject.geometries.spheres = [];
  83149. serializationObject.geometries.cylinders = [];
  83150. serializationObject.geometries.toruses = [];
  83151. serializationObject.geometries.grounds = [];
  83152. serializationObject.geometries.planes = [];
  83153. serializationObject.geometries.torusKnots = [];
  83154. serializationObject.geometries.vertexData = [];
  83155. }
  83156. serializeGeometry(geometry, serializationObject.geometries);
  83157. }
  83158. // Skeletons
  83159. if (mesh.skeleton) {
  83160. serializationObject.skeletons = serializationObject.skeletons || [];
  83161. serializationObject.skeletons.push(mesh.skeleton.serialize());
  83162. }
  83163. //serialize the actual mesh
  83164. serializationObject.meshes = serializationObject.meshes || [];
  83165. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  83166. }
  83167. };
  83168. var SceneSerializer = /** @class */ (function () {
  83169. function SceneSerializer() {
  83170. }
  83171. SceneSerializer.ClearCache = function () {
  83172. serializedGeometries = [];
  83173. };
  83174. SceneSerializer.Serialize = function (scene) {
  83175. var serializationObject = {};
  83176. SceneSerializer.ClearCache();
  83177. // Scene
  83178. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  83179. serializationObject.autoClear = scene.autoClear;
  83180. serializationObject.clearColor = scene.clearColor.asArray();
  83181. serializationObject.ambientColor = scene.ambientColor.asArray();
  83182. serializationObject.gravity = scene.gravity.asArray();
  83183. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  83184. serializationObject.workerCollisions = scene.workerCollisions;
  83185. // Fog
  83186. if (scene.fogMode && scene.fogMode !== 0) {
  83187. serializationObject.fogMode = scene.fogMode;
  83188. serializationObject.fogColor = scene.fogColor.asArray();
  83189. serializationObject.fogStart = scene.fogStart;
  83190. serializationObject.fogEnd = scene.fogEnd;
  83191. serializationObject.fogDensity = scene.fogDensity;
  83192. }
  83193. //Physics
  83194. if (scene.isPhysicsEnabled()) {
  83195. var physicEngine = scene.getPhysicsEngine();
  83196. if (physicEngine) {
  83197. serializationObject.physicsEnabled = true;
  83198. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  83199. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  83200. }
  83201. }
  83202. // Metadata
  83203. if (scene.metadata) {
  83204. serializationObject.metadata = scene.metadata;
  83205. }
  83206. // Morph targets
  83207. serializationObject.morphTargetManagers = [];
  83208. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  83209. var abstractMesh = _a[_i];
  83210. var manager = abstractMesh.morphTargetManager;
  83211. if (manager) {
  83212. serializationObject.morphTargetManagers.push(manager.serialize());
  83213. }
  83214. }
  83215. // Lights
  83216. serializationObject.lights = [];
  83217. var index;
  83218. var light;
  83219. for (index = 0; index < scene.lights.length; index++) {
  83220. light = scene.lights[index];
  83221. if (!light.doNotSerialize) {
  83222. serializationObject.lights.push(light.serialize());
  83223. }
  83224. }
  83225. // Cameras
  83226. serializationObject.cameras = [];
  83227. for (index = 0; index < scene.cameras.length; index++) {
  83228. var camera = scene.cameras[index];
  83229. if (!camera.doNotSerialize) {
  83230. serializationObject.cameras.push(camera.serialize());
  83231. }
  83232. }
  83233. if (scene.activeCamera) {
  83234. serializationObject.activeCameraID = scene.activeCamera.id;
  83235. }
  83236. // Animations
  83237. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  83238. // Materials
  83239. serializationObject.materials = [];
  83240. serializationObject.multiMaterials = [];
  83241. var material;
  83242. for (index = 0; index < scene.materials.length; index++) {
  83243. material = scene.materials[index];
  83244. if (!material.doNotSerialize) {
  83245. serializationObject.materials.push(material.serialize());
  83246. }
  83247. }
  83248. // MultiMaterials
  83249. serializationObject.multiMaterials = [];
  83250. for (index = 0; index < scene.multiMaterials.length; index++) {
  83251. var multiMaterial = scene.multiMaterials[index];
  83252. serializationObject.multiMaterials.push(multiMaterial.serialize());
  83253. }
  83254. // Environment texture
  83255. if (scene.environmentTexture) {
  83256. serializationObject.environmentTexture = scene.environmentTexture.name;
  83257. }
  83258. // Skeletons
  83259. serializationObject.skeletons = [];
  83260. for (index = 0; index < scene.skeletons.length; index++) {
  83261. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  83262. }
  83263. // Transform nodes
  83264. serializationObject.transformNodes = [];
  83265. for (index = 0; index < scene.transformNodes.length; index++) {
  83266. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  83267. }
  83268. // Geometries
  83269. serializationObject.geometries = {};
  83270. serializationObject.geometries.boxes = [];
  83271. serializationObject.geometries.spheres = [];
  83272. serializationObject.geometries.cylinders = [];
  83273. serializationObject.geometries.toruses = [];
  83274. serializationObject.geometries.grounds = [];
  83275. serializationObject.geometries.planes = [];
  83276. serializationObject.geometries.torusKnots = [];
  83277. serializationObject.geometries.vertexData = [];
  83278. serializedGeometries = [];
  83279. var geometries = scene.getGeometries();
  83280. for (index = 0; index < geometries.length; index++) {
  83281. var geometry = geometries[index];
  83282. if (geometry.isReady()) {
  83283. serializeGeometry(geometry, serializationObject.geometries);
  83284. }
  83285. }
  83286. // Meshes
  83287. serializationObject.meshes = [];
  83288. for (index = 0; index < scene.meshes.length; index++) {
  83289. var abstractMesh = scene.meshes[index];
  83290. if (abstractMesh instanceof BABYLON.Mesh) {
  83291. var mesh = abstractMesh;
  83292. if (!mesh.doNotSerialize) {
  83293. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  83294. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  83295. }
  83296. }
  83297. }
  83298. }
  83299. // Particles Systems
  83300. serializationObject.particleSystems = [];
  83301. for (index = 0; index < scene.particleSystems.length; index++) {
  83302. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  83303. }
  83304. // Lens flares
  83305. serializationObject.lensFlareSystems = [];
  83306. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  83307. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  83308. }
  83309. // Shadows
  83310. serializationObject.shadowGenerators = [];
  83311. for (index = 0; index < scene.lights.length; index++) {
  83312. light = scene.lights[index];
  83313. var shadowGenerator = light.getShadowGenerator();
  83314. if (shadowGenerator) {
  83315. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  83316. }
  83317. }
  83318. // Action Manager
  83319. if (scene.actionManager) {
  83320. serializationObject.actions = scene.actionManager.serialize("scene");
  83321. }
  83322. // Audio
  83323. serializationObject.sounds = [];
  83324. for (index = 0; index < scene.soundTracks.length; index++) {
  83325. var soundtrack = scene.soundTracks[index];
  83326. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  83327. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  83328. }
  83329. }
  83330. return serializationObject;
  83331. };
  83332. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  83333. if (withParents === void 0) { withParents = false; }
  83334. if (withChildren === void 0) { withChildren = false; }
  83335. var serializationObject = {};
  83336. SceneSerializer.ClearCache();
  83337. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  83338. if (withParents || withChildren) {
  83339. //deliberate for loop! not for each, appended should be processed as well.
  83340. for (var i = 0; i < toSerialize.length; ++i) {
  83341. if (withChildren) {
  83342. toSerialize[i].getDescendants().forEach(function (node) {
  83343. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  83344. toSerialize.push(node);
  83345. }
  83346. });
  83347. }
  83348. //make sure the array doesn't contain the object already
  83349. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  83350. toSerialize.push(toSerialize[i].parent);
  83351. }
  83352. }
  83353. }
  83354. toSerialize.forEach(function (mesh) {
  83355. finalizeSingleMesh(mesh, serializationObject);
  83356. });
  83357. return serializationObject;
  83358. };
  83359. return SceneSerializer;
  83360. }());
  83361. BABYLON.SceneSerializer = SceneSerializer;
  83362. })(BABYLON || (BABYLON = {}));
  83363. //# sourceMappingURL=babylon.sceneSerializer.js.map
  83364. var BABYLON;
  83365. (function (BABYLON) {
  83366. var ReflectionProbe = /** @class */ (function () {
  83367. function ReflectionProbe(name, size, scene, generateMipMaps) {
  83368. if (generateMipMaps === void 0) { generateMipMaps = true; }
  83369. var _this = this;
  83370. this.name = name;
  83371. this._viewMatrix = BABYLON.Matrix.Identity();
  83372. this._target = BABYLON.Vector3.Zero();
  83373. this._add = BABYLON.Vector3.Zero();
  83374. this.invertYAxis = false;
  83375. this.position = BABYLON.Vector3.Zero();
  83376. this._scene = scene;
  83377. this._scene.reflectionProbes.push(this);
  83378. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  83379. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  83380. switch (faceIndex) {
  83381. case 0:
  83382. _this._add.copyFromFloats(1, 0, 0);
  83383. break;
  83384. case 1:
  83385. _this._add.copyFromFloats(-1, 0, 0);
  83386. break;
  83387. case 2:
  83388. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  83389. break;
  83390. case 3:
  83391. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  83392. break;
  83393. case 4:
  83394. _this._add.copyFromFloats(0, 0, 1);
  83395. break;
  83396. case 5:
  83397. _this._add.copyFromFloats(0, 0, -1);
  83398. break;
  83399. }
  83400. if (_this._attachedMesh) {
  83401. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  83402. }
  83403. _this.position.addToRef(_this._add, _this._target);
  83404. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  83405. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  83406. scene._forcedViewPosition = _this.position;
  83407. });
  83408. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  83409. scene._forcedViewPosition = null;
  83410. scene.updateTransformMatrix(true);
  83411. });
  83412. if (scene.activeCamera) {
  83413. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  83414. }
  83415. }
  83416. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  83417. get: function () {
  83418. return this._renderTargetTexture.samples;
  83419. },
  83420. set: function (value) {
  83421. this._renderTargetTexture.samples = value;
  83422. },
  83423. enumerable: true,
  83424. configurable: true
  83425. });
  83426. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  83427. get: function () {
  83428. return this._renderTargetTexture.refreshRate;
  83429. },
  83430. set: function (value) {
  83431. this._renderTargetTexture.refreshRate = value;
  83432. },
  83433. enumerable: true,
  83434. configurable: true
  83435. });
  83436. ReflectionProbe.prototype.getScene = function () {
  83437. return this._scene;
  83438. };
  83439. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  83440. get: function () {
  83441. return this._renderTargetTexture;
  83442. },
  83443. enumerable: true,
  83444. configurable: true
  83445. });
  83446. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  83447. get: function () {
  83448. return this._renderTargetTexture.renderList;
  83449. },
  83450. enumerable: true,
  83451. configurable: true
  83452. });
  83453. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  83454. this._attachedMesh = mesh;
  83455. };
  83456. /**
  83457. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  83458. *
  83459. * @param renderingGroupId The rendering group id corresponding to its index
  83460. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  83461. */
  83462. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  83463. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  83464. };
  83465. ReflectionProbe.prototype.dispose = function () {
  83466. var index = this._scene.reflectionProbes.indexOf(this);
  83467. if (index !== -1) {
  83468. // Remove from the scene if found
  83469. this._scene.reflectionProbes.splice(index, 1);
  83470. }
  83471. if (this._renderTargetTexture) {
  83472. this._renderTargetTexture.dispose();
  83473. this._renderTargetTexture = null;
  83474. }
  83475. };
  83476. return ReflectionProbe;
  83477. }());
  83478. BABYLON.ReflectionProbe = ReflectionProbe;
  83479. })(BABYLON || (BABYLON = {}));
  83480. //# sourceMappingURL=babylon.reflectionProbe.js.map
  83481. var BABYLON;
  83482. (function (BABYLON) {
  83483. var Layer = /** @class */ (function () {
  83484. function Layer(name, imgUrl, scene, isBackground, color) {
  83485. this.name = name;
  83486. this.scale = new BABYLON.Vector2(1, 1);
  83487. this.offset = new BABYLON.Vector2(0, 0);
  83488. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  83489. this.layerMask = 0x0FFFFFFF;
  83490. this._vertexBuffers = {};
  83491. // Events
  83492. /**
  83493. * An event triggered when the layer is disposed.
  83494. * @type {BABYLON.Observable}
  83495. */
  83496. this.onDisposeObservable = new BABYLON.Observable();
  83497. /**
  83498. * An event triggered before rendering the scene
  83499. * @type {BABYLON.Observable}
  83500. */
  83501. this.onBeforeRenderObservable = new BABYLON.Observable();
  83502. /**
  83503. * An event triggered after rendering the scene
  83504. * @type {BABYLON.Observable}
  83505. */
  83506. this.onAfterRenderObservable = new BABYLON.Observable();
  83507. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  83508. this.isBackground = isBackground === undefined ? true : isBackground;
  83509. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  83510. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  83511. this._scene.layers.push(this);
  83512. var engine = this._scene.getEngine();
  83513. // VBO
  83514. var vertices = [];
  83515. vertices.push(1, 1);
  83516. vertices.push(-1, 1);
  83517. vertices.push(-1, -1);
  83518. vertices.push(1, -1);
  83519. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  83520. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  83521. this._createIndexBuffer();
  83522. // Effects
  83523. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  83524. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  83525. }
  83526. Object.defineProperty(Layer.prototype, "onDispose", {
  83527. set: function (callback) {
  83528. if (this._onDisposeObserver) {
  83529. this.onDisposeObservable.remove(this._onDisposeObserver);
  83530. }
  83531. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  83532. },
  83533. enumerable: true,
  83534. configurable: true
  83535. });
  83536. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  83537. set: function (callback) {
  83538. if (this._onBeforeRenderObserver) {
  83539. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  83540. }
  83541. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  83542. },
  83543. enumerable: true,
  83544. configurable: true
  83545. });
  83546. Object.defineProperty(Layer.prototype, "onAfterRender", {
  83547. set: function (callback) {
  83548. if (this._onAfterRenderObserver) {
  83549. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  83550. }
  83551. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  83552. },
  83553. enumerable: true,
  83554. configurable: true
  83555. });
  83556. Layer.prototype._createIndexBuffer = function () {
  83557. var engine = this._scene.getEngine();
  83558. // Indices
  83559. var indices = [];
  83560. indices.push(0);
  83561. indices.push(1);
  83562. indices.push(2);
  83563. indices.push(0);
  83564. indices.push(2);
  83565. indices.push(3);
  83566. this._indexBuffer = engine.createIndexBuffer(indices);
  83567. };
  83568. Layer.prototype._rebuild = function () {
  83569. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83570. if (vb) {
  83571. vb._rebuild();
  83572. }
  83573. this._createIndexBuffer();
  83574. };
  83575. Layer.prototype.render = function () {
  83576. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  83577. // Check
  83578. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  83579. return;
  83580. var engine = this._scene.getEngine();
  83581. this.onBeforeRenderObservable.notifyObservers(this);
  83582. // Render
  83583. engine.enableEffect(currentEffect);
  83584. engine.setState(false);
  83585. // Texture
  83586. currentEffect.setTexture("textureSampler", this.texture);
  83587. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  83588. // Color
  83589. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  83590. // Scale / offset
  83591. currentEffect.setVector2("offset", this.offset);
  83592. currentEffect.setVector2("scale", this.scale);
  83593. // VBOs
  83594. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  83595. // Draw order
  83596. if (!this.alphaTest) {
  83597. engine.setAlphaMode(this.alphaBlendingMode);
  83598. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83599. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  83600. }
  83601. else {
  83602. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83603. }
  83604. this.onAfterRenderObservable.notifyObservers(this);
  83605. };
  83606. Layer.prototype.dispose = function () {
  83607. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83608. if (vertexBuffer) {
  83609. vertexBuffer.dispose();
  83610. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  83611. }
  83612. if (this._indexBuffer) {
  83613. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  83614. this._indexBuffer = null;
  83615. }
  83616. if (this.texture) {
  83617. this.texture.dispose();
  83618. this.texture = null;
  83619. }
  83620. // Remove from scene
  83621. var index = this._scene.layers.indexOf(this);
  83622. this._scene.layers.splice(index, 1);
  83623. // Callback
  83624. this.onDisposeObservable.notifyObservers(this);
  83625. this.onDisposeObservable.clear();
  83626. this.onAfterRenderObservable.clear();
  83627. this.onBeforeRenderObservable.clear();
  83628. };
  83629. return Layer;
  83630. }());
  83631. BABYLON.Layer = Layer;
  83632. })(BABYLON || (BABYLON = {}));
  83633. //# sourceMappingURL=babylon.layer.js.map
  83634. var BABYLON;
  83635. (function (BABYLON) {
  83636. var TextureTools = /** @class */ (function () {
  83637. function TextureTools() {
  83638. }
  83639. /**
  83640. * Uses the GPU to create a copy texture rescaled at a given size
  83641. * @param texture Texture to copy from
  83642. * @param width Desired width
  83643. * @param height Desired height
  83644. * @return Generated texture
  83645. */
  83646. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  83647. if (useBilinearMode === void 0) { useBilinearMode = true; }
  83648. var scene = texture.getScene();
  83649. var engine = scene.getEngine();
  83650. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  83651. rtt.wrapU = texture.wrapU;
  83652. rtt.wrapV = texture.wrapV;
  83653. rtt.uOffset = texture.uOffset;
  83654. rtt.vOffset = texture.vOffset;
  83655. rtt.uScale = texture.uScale;
  83656. rtt.vScale = texture.vScale;
  83657. rtt.uAng = texture.uAng;
  83658. rtt.vAng = texture.vAng;
  83659. rtt.wAng = texture.wAng;
  83660. rtt.coordinatesIndex = texture.coordinatesIndex;
  83661. rtt.level = texture.level;
  83662. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  83663. rtt._texture.isReady = false;
  83664. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83665. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83666. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  83667. passPostProcess.getEffect().executeWhenCompiled(function () {
  83668. passPostProcess.onApply = function (effect) {
  83669. effect.setTexture("textureSampler", texture);
  83670. };
  83671. var internalTexture = rtt.getInternalTexture();
  83672. if (internalTexture) {
  83673. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  83674. engine.unBindFramebuffer(internalTexture);
  83675. rtt.disposeFramebufferObjects();
  83676. passPostProcess.dispose();
  83677. internalTexture.isReady = true;
  83678. }
  83679. });
  83680. return rtt;
  83681. };
  83682. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  83683. if (!scene._environmentBRDFTexture) {
  83684. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83685. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83686. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83687. scene._environmentBRDFTexture = texture;
  83688. }
  83689. return scene._environmentBRDFTexture;
  83690. };
  83691. 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=";
  83692. return TextureTools;
  83693. }());
  83694. BABYLON.TextureTools = TextureTools;
  83695. })(BABYLON || (BABYLON = {}));
  83696. //# sourceMappingURL=babylon.textureTools.js.map
  83697. var BABYLON;
  83698. (function (BABYLON) {
  83699. var FramingBehavior = /** @class */ (function () {
  83700. function FramingBehavior() {
  83701. this._mode = FramingBehavior.FitFrustumSidesMode;
  83702. this._radiusScale = 1.0;
  83703. this._positionScale = 0.5;
  83704. this._defaultElevation = 0.3;
  83705. this._elevationReturnTime = 1500;
  83706. this._elevationReturnWaitTime = 1000;
  83707. this._zoomStopsAnimation = false;
  83708. this._framingTime = 1500;
  83709. this._isPointerDown = false;
  83710. this._lastInteractionTime = -Infinity;
  83711. // Framing control
  83712. this._animatables = new Array();
  83713. this._betaIsAnimating = false;
  83714. }
  83715. Object.defineProperty(FramingBehavior.prototype, "name", {
  83716. get: function () {
  83717. return "Framing";
  83718. },
  83719. enumerable: true,
  83720. configurable: true
  83721. });
  83722. Object.defineProperty(FramingBehavior.prototype, "mode", {
  83723. /**
  83724. * Gets current mode used by the behavior.
  83725. */
  83726. get: function () {
  83727. return this._mode;
  83728. },
  83729. /**
  83730. * Sets the current mode used by the behavior
  83731. */
  83732. set: function (mode) {
  83733. this._mode = mode;
  83734. },
  83735. enumerable: true,
  83736. configurable: true
  83737. });
  83738. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  83739. /**
  83740. * Gets the scale applied to the radius
  83741. */
  83742. get: function () {
  83743. return this._radiusScale;
  83744. },
  83745. /**
  83746. * Sets the scale applied to the radius (1 by default)
  83747. */
  83748. set: function (radius) {
  83749. this._radiusScale = radius;
  83750. },
  83751. enumerable: true,
  83752. configurable: true
  83753. });
  83754. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  83755. /**
  83756. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  83757. */
  83758. get: function () {
  83759. return this._positionScale;
  83760. },
  83761. /**
  83762. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  83763. */
  83764. set: function (scale) {
  83765. this._positionScale = scale;
  83766. },
  83767. enumerable: true,
  83768. configurable: true
  83769. });
  83770. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  83771. /**
  83772. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  83773. * behaviour is triggered, in radians.
  83774. */
  83775. get: function () {
  83776. return this._defaultElevation;
  83777. },
  83778. /**
  83779. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  83780. * behaviour is triggered, in radians.
  83781. */
  83782. set: function (elevation) {
  83783. this._defaultElevation = elevation;
  83784. },
  83785. enumerable: true,
  83786. configurable: true
  83787. });
  83788. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  83789. /**
  83790. * Gets the time (in milliseconds) taken to return to the default beta position.
  83791. * Negative value indicates camera should not return to default.
  83792. */
  83793. get: function () {
  83794. return this._elevationReturnTime;
  83795. },
  83796. /**
  83797. * Sets the time (in milliseconds) taken to return to the default beta position.
  83798. * Negative value indicates camera should not return to default.
  83799. */
  83800. set: function (speed) {
  83801. this._elevationReturnTime = speed;
  83802. },
  83803. enumerable: true,
  83804. configurable: true
  83805. });
  83806. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  83807. /**
  83808. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  83809. */
  83810. get: function () {
  83811. return this._elevationReturnWaitTime;
  83812. },
  83813. /**
  83814. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  83815. */
  83816. set: function (time) {
  83817. this._elevationReturnWaitTime = time;
  83818. },
  83819. enumerable: true,
  83820. configurable: true
  83821. });
  83822. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  83823. /**
  83824. * Gets the flag that indicates if user zooming should stop animation.
  83825. */
  83826. get: function () {
  83827. return this._zoomStopsAnimation;
  83828. },
  83829. /**
  83830. * Sets the flag that indicates if user zooming should stop animation.
  83831. */
  83832. set: function (flag) {
  83833. this._zoomStopsAnimation = flag;
  83834. },
  83835. enumerable: true,
  83836. configurable: true
  83837. });
  83838. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  83839. /**
  83840. * Gets the transition time when framing the mesh, in milliseconds
  83841. */
  83842. get: function () {
  83843. return this._framingTime;
  83844. },
  83845. /**
  83846. * Sets the transition time when framing the mesh, in milliseconds
  83847. */
  83848. set: function (time) {
  83849. this._framingTime = time;
  83850. },
  83851. enumerable: true,
  83852. configurable: true
  83853. });
  83854. FramingBehavior.prototype.init = function () {
  83855. // Do notihng
  83856. };
  83857. FramingBehavior.prototype.attach = function (camera) {
  83858. var _this = this;
  83859. this._attachedCamera = camera;
  83860. var scene = this._attachedCamera.getScene();
  83861. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  83862. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  83863. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  83864. _this._isPointerDown = true;
  83865. return;
  83866. }
  83867. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  83868. _this._isPointerDown = false;
  83869. }
  83870. });
  83871. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  83872. if (mesh) {
  83873. _this.zoomOnMesh(mesh);
  83874. }
  83875. });
  83876. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  83877. // Stop the animation if there is user interaction and the animation should stop for this interaction
  83878. _this._applyUserInteraction();
  83879. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  83880. // back to the default position after a given timeout
  83881. _this._maintainCameraAboveGround();
  83882. });
  83883. };
  83884. FramingBehavior.prototype.detach = function () {
  83885. if (!this._attachedCamera) {
  83886. return;
  83887. }
  83888. var scene = this._attachedCamera.getScene();
  83889. if (this._onPrePointerObservableObserver) {
  83890. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  83891. }
  83892. if (this._onAfterCheckInputsObserver) {
  83893. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  83894. }
  83895. if (this._onMeshTargetChangedObserver) {
  83896. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  83897. }
  83898. this._attachedCamera = null;
  83899. };
  83900. /**
  83901. * Targets the given mesh and updates zoom level accordingly.
  83902. * @param mesh The mesh to target.
  83903. * @param radius Optional. If a cached radius position already exists, overrides default.
  83904. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  83905. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  83906. * @param onAnimationEnd Callback triggered at the end of the framing animation
  83907. */
  83908. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  83909. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  83910. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  83911. mesh.computeWorldMatrix(true);
  83912. var boundingBox = mesh.getBoundingInfo().boundingBox;
  83913. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  83914. };
  83915. /**
  83916. * Targets the given mesh with its children and updates zoom level accordingly.
  83917. * @param mesh The mesh to target.
  83918. * @param radius Optional. If a cached radius position already exists, overrides default.
  83919. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  83920. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  83921. * @param onAnimationEnd Callback triggered at the end of the framing animation
  83922. */
  83923. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  83924. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  83925. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  83926. mesh.computeWorldMatrix(true);
  83927. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  83928. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  83929. };
  83930. /**
  83931. * Targets the given meshes with their children and updates zoom level accordingly.
  83932. * @param meshes The mesh to target.
  83933. * @param radius Optional. If a cached radius position already exists, overrides default.
  83934. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  83935. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  83936. * @param onAnimationEnd Callback triggered at the end of the framing animation
  83937. */
  83938. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  83939. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  83940. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  83941. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  83942. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  83943. for (var i = 0; i < meshes.length; i++) {
  83944. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  83945. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  83946. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  83947. }
  83948. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  83949. };
  83950. /**
  83951. * Targets the given mesh and updates zoom level accordingly.
  83952. * @param mesh The mesh to target.
  83953. * @param radius Optional. If a cached radius position already exists, overrides default.
  83954. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  83955. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  83956. * @param onAnimationEnd Callback triggered at the end of the framing animation
  83957. */
  83958. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  83959. var _this = this;
  83960. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  83961. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  83962. var zoomTarget;
  83963. if (!this._attachedCamera) {
  83964. return;
  83965. }
  83966. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  83967. var bottom = minimumWorld.y;
  83968. var top = maximumWorld.y;
  83969. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  83970. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  83971. if (focusOnOriginXZ) {
  83972. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  83973. }
  83974. else {
  83975. var centerWorld = minimumWorld.add(radiusWorld);
  83976. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  83977. }
  83978. if (!this._vectorTransition) {
  83979. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  83980. }
  83981. this._betaIsAnimating = true;
  83982. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  83983. if (animatable) {
  83984. this._animatables.push(animatable);
  83985. }
  83986. // sets the radius and lower radius bounds
  83987. // Small delta ensures camera is not always at lower zoom limit.
  83988. var radius = 0;
  83989. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  83990. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  83991. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  83992. radius = position;
  83993. }
  83994. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  83995. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  83996. if (this._attachedCamera.lowerRadiusLimit === null) {
  83997. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  83998. }
  83999. }
  84000. // Set sensibilities
  84001. var extend = maximumWorld.subtract(minimumWorld).length();
  84002. this._attachedCamera.panningSensibility = 5000 / extend;
  84003. this._attachedCamera.wheelPrecision = 100 / radius;
  84004. // transition to new radius
  84005. if (!this._radiusTransition) {
  84006. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  84007. }
  84008. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  84009. if (onAnimationEnd) {
  84010. onAnimationEnd();
  84011. }
  84012. if (_this._attachedCamera) {
  84013. _this._attachedCamera.storeState();
  84014. }
  84015. });
  84016. if (animatable) {
  84017. this._animatables.push(animatable);
  84018. }
  84019. };
  84020. /**
  84021. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  84022. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  84023. * frustum width.
  84024. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  84025. * to fully enclose the mesh in the viewing frustum.
  84026. */
  84027. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  84028. var size = maximumWorld.subtract(minimumWorld);
  84029. var boxVectorGlobalDiagonal = size.length();
  84030. var frustumSlope = this._getFrustumSlope();
  84031. // Formula for setting distance
  84032. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  84033. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  84034. // Horizon distance
  84035. var radius = radiusWithoutFraming * this._radiusScale;
  84036. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  84037. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  84038. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  84039. var camera = this._attachedCamera;
  84040. if (!camera) {
  84041. return 0;
  84042. }
  84043. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  84044. // Don't exceed the requested limit
  84045. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  84046. }
  84047. // Don't exceed the upper radius limit
  84048. if (camera.upperRadiusLimit) {
  84049. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  84050. }
  84051. return distance;
  84052. };
  84053. /**
  84054. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  84055. * is automatically returned to its default position (expected to be above ground plane).
  84056. */
  84057. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  84058. var _this = this;
  84059. if (this._elevationReturnTime < 0) {
  84060. return;
  84061. }
  84062. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  84063. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  84064. var limitBeta = Math.PI * 0.5;
  84065. // Bring the camera back up if below the ground plane
  84066. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  84067. this._betaIsAnimating = true;
  84068. //Transition to new position
  84069. this.stopAllAnimations();
  84070. if (!this._betaTransition) {
  84071. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  84072. }
  84073. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  84074. _this._clearAnimationLocks();
  84075. _this.stopAllAnimations();
  84076. });
  84077. if (animatabe) {
  84078. this._animatables.push(animatabe);
  84079. }
  84080. }
  84081. };
  84082. /**
  84083. * Returns the frustum slope based on the canvas ratio and camera FOV
  84084. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  84085. */
  84086. FramingBehavior.prototype._getFrustumSlope = function () {
  84087. // Calculate the viewport ratio
  84088. // Aspect Ratio is Height/Width.
  84089. var camera = this._attachedCamera;
  84090. if (!camera) {
  84091. return BABYLON.Vector2.Zero();
  84092. }
  84093. var engine = camera.getScene().getEngine();
  84094. var aspectRatio = engine.getAspectRatio(camera);
  84095. // Camera FOV is the vertical field of view (top-bottom) in radians.
  84096. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  84097. var frustumSlopeY = Math.tan(camera.fov / 2);
  84098. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  84099. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  84100. // along the forward vector.
  84101. var frustumSlopeX = frustumSlopeY * aspectRatio;
  84102. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  84103. };
  84104. /**
  84105. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  84106. */
  84107. FramingBehavior.prototype._clearAnimationLocks = function () {
  84108. this._betaIsAnimating = false;
  84109. };
  84110. /**
  84111. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  84112. */
  84113. FramingBehavior.prototype._applyUserInteraction = function () {
  84114. if (this.isUserIsMoving) {
  84115. this._lastInteractionTime = BABYLON.Tools.Now;
  84116. this.stopAllAnimations();
  84117. this._clearAnimationLocks();
  84118. }
  84119. };
  84120. /**
  84121. * Stops and removes all animations that have been applied to the camera
  84122. */
  84123. FramingBehavior.prototype.stopAllAnimations = function () {
  84124. if (this._attachedCamera) {
  84125. this._attachedCamera.animations = [];
  84126. }
  84127. while (this._animatables.length) {
  84128. if (this._animatables[0]) {
  84129. this._animatables[0].onAnimationEnd = null;
  84130. this._animatables[0].stop();
  84131. }
  84132. this._animatables.shift();
  84133. }
  84134. };
  84135. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  84136. /**
  84137. * Gets a value indicating if the user is moving the camera
  84138. */
  84139. get: function () {
  84140. if (!this._attachedCamera) {
  84141. return false;
  84142. }
  84143. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  84144. this._attachedCamera.inertialBetaOffset !== 0 ||
  84145. this._attachedCamera.inertialRadiusOffset !== 0 ||
  84146. this._attachedCamera.inertialPanningX !== 0 ||
  84147. this._attachedCamera.inertialPanningY !== 0 ||
  84148. this._isPointerDown;
  84149. },
  84150. enumerable: true,
  84151. configurable: true
  84152. });
  84153. /**
  84154. * The easing function used by animations
  84155. */
  84156. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  84157. /**
  84158. * The easing mode used by animations
  84159. */
  84160. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  84161. // Statics
  84162. /**
  84163. * The camera can move all the way towards the mesh.
  84164. */
  84165. FramingBehavior.IgnoreBoundsSizeMode = 0;
  84166. /**
  84167. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  84168. */
  84169. FramingBehavior.FitFrustumSidesMode = 1;
  84170. return FramingBehavior;
  84171. }());
  84172. BABYLON.FramingBehavior = FramingBehavior;
  84173. })(BABYLON || (BABYLON = {}));
  84174. //# sourceMappingURL=babylon.framingBehavior.js.map
  84175. var BABYLON;
  84176. (function (BABYLON) {
  84177. /**
  84178. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  84179. */
  84180. var BouncingBehavior = /** @class */ (function () {
  84181. function BouncingBehavior() {
  84182. /**
  84183. * The duration of the animation, in milliseconds
  84184. */
  84185. this.transitionDuration = 450;
  84186. /**
  84187. * Length of the distance animated by the transition when lower radius is reached
  84188. */
  84189. this.lowerRadiusTransitionRange = 2;
  84190. /**
  84191. * Length of the distance animated by the transition when upper radius is reached
  84192. */
  84193. this.upperRadiusTransitionRange = -2;
  84194. this._autoTransitionRange = false;
  84195. // Animations
  84196. this._radiusIsAnimating = false;
  84197. this._radiusBounceTransition = null;
  84198. this._animatables = new Array();
  84199. }
  84200. Object.defineProperty(BouncingBehavior.prototype, "name", {
  84201. get: function () {
  84202. return "Bouncing";
  84203. },
  84204. enumerable: true,
  84205. configurable: true
  84206. });
  84207. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  84208. /**
  84209. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  84210. */
  84211. get: function () {
  84212. return this._autoTransitionRange;
  84213. },
  84214. /**
  84215. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  84216. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  84217. */
  84218. set: function (value) {
  84219. var _this = this;
  84220. if (this._autoTransitionRange === value) {
  84221. return;
  84222. }
  84223. this._autoTransitionRange = value;
  84224. var camera = this._attachedCamera;
  84225. if (!camera) {
  84226. return;
  84227. }
  84228. if (value) {
  84229. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  84230. if (!mesh) {
  84231. return;
  84232. }
  84233. mesh.computeWorldMatrix(true);
  84234. var diagonal = mesh.getBoundingInfo().diagonalLength;
  84235. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  84236. _this.upperRadiusTransitionRange = diagonal * 0.05;
  84237. });
  84238. }
  84239. else if (this._onMeshTargetChangedObserver) {
  84240. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  84241. }
  84242. },
  84243. enumerable: true,
  84244. configurable: true
  84245. });
  84246. BouncingBehavior.prototype.init = function () {
  84247. // Do notihng
  84248. };
  84249. BouncingBehavior.prototype.attach = function (camera) {
  84250. var _this = this;
  84251. this._attachedCamera = camera;
  84252. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  84253. if (!_this._attachedCamera) {
  84254. return;
  84255. }
  84256. // Add the bounce animation to the lower radius limit
  84257. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  84258. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  84259. }
  84260. // Add the bounce animation to the upper radius limit
  84261. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  84262. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  84263. }
  84264. });
  84265. };
  84266. BouncingBehavior.prototype.detach = function () {
  84267. if (!this._attachedCamera) {
  84268. return;
  84269. }
  84270. if (this._onAfterCheckInputsObserver) {
  84271. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  84272. }
  84273. if (this._onMeshTargetChangedObserver) {
  84274. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  84275. }
  84276. this._attachedCamera = null;
  84277. };
  84278. /**
  84279. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  84280. * @param radiusLimit The limit to check against.
  84281. * @return Bool to indicate if at limit.
  84282. */
  84283. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  84284. if (!this._attachedCamera) {
  84285. return false;
  84286. }
  84287. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  84288. return true;
  84289. }
  84290. return false;
  84291. };
  84292. /**
  84293. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  84294. * @param radiusDelta The delta by which to animate to. Can be negative.
  84295. */
  84296. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  84297. var _this = this;
  84298. if (!this._attachedCamera) {
  84299. return;
  84300. }
  84301. if (!this._radiusBounceTransition) {
  84302. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  84303. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  84304. }
  84305. // Prevent zoom until bounce has completed
  84306. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  84307. this._attachedCamera.wheelPrecision = Infinity;
  84308. this._attachedCamera.inertialRadiusOffset = 0;
  84309. // Animate to the radius limit
  84310. this.stopAllAnimations();
  84311. this._radiusIsAnimating = true;
  84312. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  84313. if (animatable) {
  84314. this._animatables.push(animatable);
  84315. }
  84316. };
  84317. /**
  84318. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  84319. */
  84320. BouncingBehavior.prototype._clearAnimationLocks = function () {
  84321. this._radiusIsAnimating = false;
  84322. if (this._attachedCamera) {
  84323. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  84324. }
  84325. };
  84326. /**
  84327. * Stops and removes all animations that have been applied to the camera
  84328. */
  84329. BouncingBehavior.prototype.stopAllAnimations = function () {
  84330. if (this._attachedCamera) {
  84331. this._attachedCamera.animations = [];
  84332. }
  84333. while (this._animatables.length) {
  84334. this._animatables[0].onAnimationEnd = null;
  84335. this._animatables[0].stop();
  84336. this._animatables.shift();
  84337. }
  84338. };
  84339. /**
  84340. * The easing function used by animations
  84341. */
  84342. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  84343. /**
  84344. * The easing mode used by animations
  84345. */
  84346. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  84347. return BouncingBehavior;
  84348. }());
  84349. BABYLON.BouncingBehavior = BouncingBehavior;
  84350. })(BABYLON || (BABYLON = {}));
  84351. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  84352. var BABYLON;
  84353. (function (BABYLON) {
  84354. var AutoRotationBehavior = /** @class */ (function () {
  84355. function AutoRotationBehavior() {
  84356. this._zoomStopsAnimation = false;
  84357. this._idleRotationSpeed = 0.05;
  84358. this._idleRotationWaitTime = 2000;
  84359. this._idleRotationSpinupTime = 2000;
  84360. this._isPointerDown = false;
  84361. this._lastFrameTime = null;
  84362. this._lastInteractionTime = -Infinity;
  84363. this._cameraRotationSpeed = 0;
  84364. this._lastFrameRadius = 0;
  84365. }
  84366. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  84367. get: function () {
  84368. return "AutoRotation";
  84369. },
  84370. enumerable: true,
  84371. configurable: true
  84372. });
  84373. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  84374. /**
  84375. * Gets the flag that indicates if user zooming should stop animation.
  84376. */
  84377. get: function () {
  84378. return this._zoomStopsAnimation;
  84379. },
  84380. /**
  84381. * Sets the flag that indicates if user zooming should stop animation.
  84382. */
  84383. set: function (flag) {
  84384. this._zoomStopsAnimation = flag;
  84385. },
  84386. enumerable: true,
  84387. configurable: true
  84388. });
  84389. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  84390. /**
  84391. * Gets the default speed at which the camera rotates around the model.
  84392. */
  84393. get: function () {
  84394. return this._idleRotationSpeed;
  84395. },
  84396. /**
  84397. * Sets the default speed at which the camera rotates around the model.
  84398. */
  84399. set: function (speed) {
  84400. this._idleRotationSpeed = speed;
  84401. },
  84402. enumerable: true,
  84403. configurable: true
  84404. });
  84405. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  84406. /**
  84407. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  84408. */
  84409. get: function () {
  84410. return this._idleRotationWaitTime;
  84411. },
  84412. /**
  84413. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  84414. */
  84415. set: function (time) {
  84416. this._idleRotationWaitTime = time;
  84417. },
  84418. enumerable: true,
  84419. configurable: true
  84420. });
  84421. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  84422. /**
  84423. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  84424. */
  84425. get: function () {
  84426. return this._idleRotationSpinupTime;
  84427. },
  84428. /**
  84429. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  84430. */
  84431. set: function (time) {
  84432. this._idleRotationSpinupTime = time;
  84433. },
  84434. enumerable: true,
  84435. configurable: true
  84436. });
  84437. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  84438. /**
  84439. * Gets a value indicating if the camera is currently rotating because of this behavior
  84440. */
  84441. get: function () {
  84442. return Math.abs(this._cameraRotationSpeed) > 0;
  84443. },
  84444. enumerable: true,
  84445. configurable: true
  84446. });
  84447. AutoRotationBehavior.prototype.init = function () {
  84448. // Do notihng
  84449. };
  84450. AutoRotationBehavior.prototype.attach = function (camera) {
  84451. var _this = this;
  84452. this._attachedCamera = camera;
  84453. var scene = this._attachedCamera.getScene();
  84454. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  84455. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  84456. _this._isPointerDown = true;
  84457. return;
  84458. }
  84459. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  84460. _this._isPointerDown = false;
  84461. }
  84462. });
  84463. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  84464. var now = BABYLON.Tools.Now;
  84465. var dt = 0;
  84466. if (_this._lastFrameTime != null) {
  84467. dt = now - _this._lastFrameTime;
  84468. }
  84469. _this._lastFrameTime = now;
  84470. // Stop the animation if there is user interaction and the animation should stop for this interaction
  84471. _this._applyUserInteraction();
  84472. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  84473. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  84474. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  84475. // Step camera rotation by rotation speed
  84476. if (_this._attachedCamera) {
  84477. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  84478. }
  84479. });
  84480. };
  84481. AutoRotationBehavior.prototype.detach = function () {
  84482. if (!this._attachedCamera) {
  84483. return;
  84484. }
  84485. var scene = this._attachedCamera.getScene();
  84486. if (this._onPrePointerObservableObserver) {
  84487. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  84488. }
  84489. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  84490. this._attachedCamera = null;
  84491. };
  84492. /**
  84493. * Returns true if user is scrolling.
  84494. * @return true if user is scrolling.
  84495. */
  84496. AutoRotationBehavior.prototype._userIsZooming = function () {
  84497. if (!this._attachedCamera) {
  84498. return false;
  84499. }
  84500. return this._attachedCamera.inertialRadiusOffset !== 0;
  84501. };
  84502. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  84503. if (!this._attachedCamera) {
  84504. return false;
  84505. }
  84506. var zoomHasHitLimit = false;
  84507. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  84508. zoomHasHitLimit = true;
  84509. }
  84510. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  84511. this._lastFrameRadius = this._attachedCamera.radius;
  84512. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  84513. };
  84514. /**
  84515. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  84516. */
  84517. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  84518. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  84519. this._lastInteractionTime = BABYLON.Tools.Now;
  84520. }
  84521. };
  84522. // Tools
  84523. AutoRotationBehavior.prototype._userIsMoving = function () {
  84524. if (!this._attachedCamera) {
  84525. return false;
  84526. }
  84527. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  84528. this._attachedCamera.inertialBetaOffset !== 0 ||
  84529. this._attachedCamera.inertialRadiusOffset !== 0 ||
  84530. this._attachedCamera.inertialPanningX !== 0 ||
  84531. this._attachedCamera.inertialPanningY !== 0 ||
  84532. this._isPointerDown;
  84533. };
  84534. return AutoRotationBehavior;
  84535. }());
  84536. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  84537. })(BABYLON || (BABYLON = {}));
  84538. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  84539. var BABYLON;
  84540. (function (BABYLON) {
  84541. /**
  84542. * This class can be used to get instrumentation data from a Babylon engine
  84543. */
  84544. var EngineInstrumentation = /** @class */ (function () {
  84545. function EngineInstrumentation(engine) {
  84546. this.engine = engine;
  84547. this._captureGPUFrameTime = false;
  84548. this._gpuFrameTime = new BABYLON.PerfCounter();
  84549. this._captureShaderCompilationTime = false;
  84550. this._shaderCompilationTime = new BABYLON.PerfCounter();
  84551. // Observers
  84552. this._onBeginFrameObserver = null;
  84553. this._onEndFrameObserver = null;
  84554. this._onBeforeShaderCompilationObserver = null;
  84555. this._onAfterShaderCompilationObserver = null;
  84556. }
  84557. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  84558. // Properties
  84559. /**
  84560. * Gets the perf counter used for GPU frame time
  84561. */
  84562. get: function () {
  84563. return this._gpuFrameTime;
  84564. },
  84565. enumerable: true,
  84566. configurable: true
  84567. });
  84568. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  84569. /**
  84570. * Gets the GPU frame time capture status
  84571. */
  84572. get: function () {
  84573. return this._captureGPUFrameTime;
  84574. },
  84575. /**
  84576. * Enable or disable the GPU frame time capture
  84577. */
  84578. set: function (value) {
  84579. var _this = this;
  84580. if (value === this._captureGPUFrameTime) {
  84581. return;
  84582. }
  84583. this._captureGPUFrameTime = value;
  84584. if (value) {
  84585. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  84586. if (!_this._gpuFrameTimeToken) {
  84587. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  84588. }
  84589. });
  84590. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  84591. if (!_this._gpuFrameTimeToken) {
  84592. return;
  84593. }
  84594. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  84595. if (time > -1) {
  84596. _this._gpuFrameTimeToken = null;
  84597. _this._gpuFrameTime.fetchNewFrame();
  84598. _this._gpuFrameTime.addCount(time, true);
  84599. }
  84600. });
  84601. }
  84602. else {
  84603. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  84604. this._onBeginFrameObserver = null;
  84605. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  84606. this._onEndFrameObserver = null;
  84607. }
  84608. },
  84609. enumerable: true,
  84610. configurable: true
  84611. });
  84612. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  84613. /**
  84614. * Gets the perf counter used for shader compilation time
  84615. */
  84616. get: function () {
  84617. return this._shaderCompilationTime;
  84618. },
  84619. enumerable: true,
  84620. configurable: true
  84621. });
  84622. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  84623. /**
  84624. * Gets the shader compilation time capture status
  84625. */
  84626. get: function () {
  84627. return this._captureShaderCompilationTime;
  84628. },
  84629. /**
  84630. * Enable or disable the shader compilation time capture
  84631. */
  84632. set: function (value) {
  84633. var _this = this;
  84634. if (value === this._captureShaderCompilationTime) {
  84635. return;
  84636. }
  84637. this._captureShaderCompilationTime = value;
  84638. if (value) {
  84639. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  84640. _this._shaderCompilationTime.fetchNewFrame();
  84641. _this._shaderCompilationTime.beginMonitoring();
  84642. });
  84643. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  84644. _this._shaderCompilationTime.endMonitoring();
  84645. });
  84646. }
  84647. else {
  84648. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  84649. this._onBeforeShaderCompilationObserver = null;
  84650. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  84651. this._onAfterShaderCompilationObserver = null;
  84652. }
  84653. },
  84654. enumerable: true,
  84655. configurable: true
  84656. });
  84657. EngineInstrumentation.prototype.dispose = function () {
  84658. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  84659. this._onBeginFrameObserver = null;
  84660. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  84661. this._onEndFrameObserver = null;
  84662. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  84663. this._onBeforeShaderCompilationObserver = null;
  84664. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  84665. this._onAfterShaderCompilationObserver = null;
  84666. this.engine = null;
  84667. };
  84668. return EngineInstrumentation;
  84669. }());
  84670. BABYLON.EngineInstrumentation = EngineInstrumentation;
  84671. })(BABYLON || (BABYLON = {}));
  84672. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  84673. var BABYLON;
  84674. (function (BABYLON) {
  84675. /**
  84676. * This class can be used to get instrumentation data from a Babylon engine
  84677. */
  84678. var SceneInstrumentation = /** @class */ (function () {
  84679. function SceneInstrumentation(scene) {
  84680. var _this = this;
  84681. this.scene = scene;
  84682. this._captureActiveMeshesEvaluationTime = false;
  84683. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  84684. this._captureRenderTargetsRenderTime = false;
  84685. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  84686. this._captureFrameTime = false;
  84687. this._frameTime = new BABYLON.PerfCounter();
  84688. this._captureRenderTime = false;
  84689. this._renderTime = new BABYLON.PerfCounter();
  84690. this._captureInterFrameTime = false;
  84691. this._interFrameTime = new BABYLON.PerfCounter();
  84692. this._captureParticlesRenderTime = false;
  84693. this._particlesRenderTime = new BABYLON.PerfCounter();
  84694. this._captureSpritesRenderTime = false;
  84695. this._spritesRenderTime = new BABYLON.PerfCounter();
  84696. this._capturePhysicsTime = false;
  84697. this._physicsTime = new BABYLON.PerfCounter();
  84698. this._captureAnimationsTime = false;
  84699. this._animationsTime = new BABYLON.PerfCounter();
  84700. // Observers
  84701. this._onBeforeActiveMeshesEvaluationObserver = null;
  84702. this._onAfterActiveMeshesEvaluationObserver = null;
  84703. this._onBeforeRenderTargetsRenderObserver = null;
  84704. this._onAfterRenderTargetsRenderObserver = null;
  84705. this._onAfterRenderObserver = null;
  84706. this._onBeforeDrawPhaseObserver = null;
  84707. this._onAfterDrawPhaseObserver = null;
  84708. this._onBeforeAnimationsObserver = null;
  84709. this._onBeforeParticlesRenderingObserver = null;
  84710. this._onAfterParticlesRenderingObserver = null;
  84711. this._onBeforeSpritesRenderingObserver = null;
  84712. this._onAfterSpritesRenderingObserver = null;
  84713. this._onBeforePhysicsObserver = null;
  84714. this._onAfterPhysicsObserver = null;
  84715. this._onAfterAnimationsObserver = null;
  84716. // Before render
  84717. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  84718. if (_this._captureActiveMeshesEvaluationTime) {
  84719. _this._activeMeshesEvaluationTime.fetchNewFrame();
  84720. }
  84721. if (_this._captureRenderTargetsRenderTime) {
  84722. _this._renderTargetsRenderTime.fetchNewFrame();
  84723. }
  84724. if (_this._captureFrameTime) {
  84725. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  84726. _this._frameTime.beginMonitoring();
  84727. }
  84728. if (_this._captureInterFrameTime) {
  84729. _this._interFrameTime.endMonitoring();
  84730. }
  84731. if (_this._captureParticlesRenderTime) {
  84732. _this._particlesRenderTime.fetchNewFrame();
  84733. }
  84734. if (_this._captureSpritesRenderTime) {
  84735. _this._spritesRenderTime.fetchNewFrame();
  84736. }
  84737. if (_this._captureAnimationsTime) {
  84738. _this._animationsTime.beginMonitoring();
  84739. }
  84740. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  84741. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  84742. });
  84743. // After render
  84744. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  84745. if (_this._captureFrameTime) {
  84746. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  84747. _this._frameTime.endMonitoring();
  84748. }
  84749. if (_this._captureRenderTime) {
  84750. _this._renderTime.endMonitoring(false);
  84751. }
  84752. if (_this._captureInterFrameTime) {
  84753. _this._interFrameTime.beginMonitoring();
  84754. }
  84755. });
  84756. }
  84757. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  84758. // Properties
  84759. /**
  84760. * Gets the perf counter used for active meshes evaluation time
  84761. */
  84762. get: function () {
  84763. return this._activeMeshesEvaluationTime;
  84764. },
  84765. enumerable: true,
  84766. configurable: true
  84767. });
  84768. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  84769. /**
  84770. * Gets the active meshes evaluation time capture status
  84771. */
  84772. get: function () {
  84773. return this._captureActiveMeshesEvaluationTime;
  84774. },
  84775. /**
  84776. * Enable or disable the active meshes evaluation time capture
  84777. */
  84778. set: function (value) {
  84779. var _this = this;
  84780. if (value === this._captureActiveMeshesEvaluationTime) {
  84781. return;
  84782. }
  84783. this._captureActiveMeshesEvaluationTime = value;
  84784. if (value) {
  84785. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  84786. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  84787. _this._activeMeshesEvaluationTime.beginMonitoring();
  84788. });
  84789. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  84790. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  84791. _this._activeMeshesEvaluationTime.endMonitoring();
  84792. });
  84793. }
  84794. else {
  84795. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  84796. this._onBeforeActiveMeshesEvaluationObserver = null;
  84797. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  84798. this._onAfterActiveMeshesEvaluationObserver = null;
  84799. }
  84800. },
  84801. enumerable: true,
  84802. configurable: true
  84803. });
  84804. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  84805. /**
  84806. * Gets the perf counter used for render targets render time
  84807. */
  84808. get: function () {
  84809. return this._renderTargetsRenderTime;
  84810. },
  84811. enumerable: true,
  84812. configurable: true
  84813. });
  84814. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  84815. /**
  84816. * Gets the render targets render time capture status
  84817. */
  84818. get: function () {
  84819. return this._captureRenderTargetsRenderTime;
  84820. },
  84821. /**
  84822. * Enable or disable the render targets render time capture
  84823. */
  84824. set: function (value) {
  84825. var _this = this;
  84826. if (value === this._captureRenderTargetsRenderTime) {
  84827. return;
  84828. }
  84829. this._captureRenderTargetsRenderTime = value;
  84830. if (value) {
  84831. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  84832. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  84833. _this._renderTargetsRenderTime.beginMonitoring();
  84834. });
  84835. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  84836. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  84837. _this._renderTargetsRenderTime.endMonitoring(false);
  84838. });
  84839. }
  84840. else {
  84841. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  84842. this._onBeforeRenderTargetsRenderObserver = null;
  84843. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  84844. this._onAfterRenderTargetsRenderObserver = null;
  84845. }
  84846. },
  84847. enumerable: true,
  84848. configurable: true
  84849. });
  84850. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  84851. /**
  84852. * Gets the perf counter used for particles render time
  84853. */
  84854. get: function () {
  84855. return this._particlesRenderTime;
  84856. },
  84857. enumerable: true,
  84858. configurable: true
  84859. });
  84860. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  84861. /**
  84862. * Gets the particles render time capture status
  84863. */
  84864. get: function () {
  84865. return this._captureParticlesRenderTime;
  84866. },
  84867. /**
  84868. * Enable or disable the particles render time capture
  84869. */
  84870. set: function (value) {
  84871. var _this = this;
  84872. if (value === this._captureParticlesRenderTime) {
  84873. return;
  84874. }
  84875. this._captureParticlesRenderTime = value;
  84876. if (value) {
  84877. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  84878. BABYLON.Tools.StartPerformanceCounter("Particles");
  84879. _this._particlesRenderTime.beginMonitoring();
  84880. });
  84881. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  84882. BABYLON.Tools.EndPerformanceCounter("Particles");
  84883. _this._particlesRenderTime.endMonitoring(false);
  84884. });
  84885. }
  84886. else {
  84887. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  84888. this._onBeforeParticlesRenderingObserver = null;
  84889. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  84890. this._onAfterParticlesRenderingObserver = null;
  84891. }
  84892. },
  84893. enumerable: true,
  84894. configurable: true
  84895. });
  84896. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  84897. /**
  84898. * Gets the perf counter used for sprites render time
  84899. */
  84900. get: function () {
  84901. return this._spritesRenderTime;
  84902. },
  84903. enumerable: true,
  84904. configurable: true
  84905. });
  84906. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  84907. /**
  84908. * Gets the sprites render time capture status
  84909. */
  84910. get: function () {
  84911. return this._captureSpritesRenderTime;
  84912. },
  84913. /**
  84914. * Enable or disable the sprites render time capture
  84915. */
  84916. set: function (value) {
  84917. var _this = this;
  84918. if (value === this._captureSpritesRenderTime) {
  84919. return;
  84920. }
  84921. this._captureSpritesRenderTime = value;
  84922. if (value) {
  84923. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  84924. BABYLON.Tools.StartPerformanceCounter("Sprites");
  84925. _this._spritesRenderTime.beginMonitoring();
  84926. });
  84927. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  84928. BABYLON.Tools.EndPerformanceCounter("Sprites");
  84929. _this._spritesRenderTime.endMonitoring(false);
  84930. });
  84931. }
  84932. else {
  84933. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  84934. this._onBeforeSpritesRenderingObserver = null;
  84935. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  84936. this._onAfterSpritesRenderingObserver = null;
  84937. }
  84938. },
  84939. enumerable: true,
  84940. configurable: true
  84941. });
  84942. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  84943. /**
  84944. * Gets the perf counter used for physics time
  84945. */
  84946. get: function () {
  84947. return this._physicsTime;
  84948. },
  84949. enumerable: true,
  84950. configurable: true
  84951. });
  84952. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  84953. /**
  84954. * Gets the physics time capture status
  84955. */
  84956. get: function () {
  84957. return this._capturePhysicsTime;
  84958. },
  84959. /**
  84960. * Enable or disable the physics time capture
  84961. */
  84962. set: function (value) {
  84963. var _this = this;
  84964. if (value === this._capturePhysicsTime) {
  84965. return;
  84966. }
  84967. this._capturePhysicsTime = value;
  84968. if (value) {
  84969. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  84970. BABYLON.Tools.StartPerformanceCounter("Physics");
  84971. _this._physicsTime.beginMonitoring();
  84972. });
  84973. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  84974. BABYLON.Tools.EndPerformanceCounter("Physics");
  84975. _this._physicsTime.endMonitoring();
  84976. });
  84977. }
  84978. else {
  84979. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  84980. this._onBeforePhysicsObserver = null;
  84981. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  84982. this._onAfterPhysicsObserver = null;
  84983. }
  84984. },
  84985. enumerable: true,
  84986. configurable: true
  84987. });
  84988. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  84989. /**
  84990. * Gets the perf counter used for animations time
  84991. */
  84992. get: function () {
  84993. return this._animationsTime;
  84994. },
  84995. enumerable: true,
  84996. configurable: true
  84997. });
  84998. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  84999. /**
  85000. * Gets the animations time capture status
  85001. */
  85002. get: function () {
  85003. return this._captureAnimationsTime;
  85004. },
  85005. /**
  85006. * Enable or disable the animations time capture
  85007. */
  85008. set: function (value) {
  85009. var _this = this;
  85010. if (value === this._captureAnimationsTime) {
  85011. return;
  85012. }
  85013. this._captureAnimationsTime = value;
  85014. if (value) {
  85015. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  85016. _this._animationsTime.endMonitoring();
  85017. });
  85018. }
  85019. else {
  85020. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  85021. this._onAfterAnimationsObserver = null;
  85022. }
  85023. },
  85024. enumerable: true,
  85025. configurable: true
  85026. });
  85027. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  85028. /**
  85029. * Gets the perf counter used for frame time capture
  85030. */
  85031. get: function () {
  85032. return this._frameTime;
  85033. },
  85034. enumerable: true,
  85035. configurable: true
  85036. });
  85037. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  85038. /**
  85039. * Gets the frame time capture status
  85040. */
  85041. get: function () {
  85042. return this._captureFrameTime;
  85043. },
  85044. /**
  85045. * Enable or disable the frame time capture
  85046. */
  85047. set: function (value) {
  85048. this._captureFrameTime = value;
  85049. },
  85050. enumerable: true,
  85051. configurable: true
  85052. });
  85053. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  85054. /**
  85055. * Gets the perf counter used for inter-frames time capture
  85056. */
  85057. get: function () {
  85058. return this._interFrameTime;
  85059. },
  85060. enumerable: true,
  85061. configurable: true
  85062. });
  85063. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  85064. /**
  85065. * Gets the inter-frames time capture status
  85066. */
  85067. get: function () {
  85068. return this._captureInterFrameTime;
  85069. },
  85070. /**
  85071. * Enable or disable the inter-frames time capture
  85072. */
  85073. set: function (value) {
  85074. this._captureInterFrameTime = value;
  85075. },
  85076. enumerable: true,
  85077. configurable: true
  85078. });
  85079. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  85080. /**
  85081. * Gets the perf counter used for render time capture
  85082. */
  85083. get: function () {
  85084. return this._renderTime;
  85085. },
  85086. enumerable: true,
  85087. configurable: true
  85088. });
  85089. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  85090. /**
  85091. * Gets the render time capture status
  85092. */
  85093. get: function () {
  85094. return this._captureRenderTime;
  85095. },
  85096. /**
  85097. * Enable or disable the render time capture
  85098. */
  85099. set: function (value) {
  85100. var _this = this;
  85101. if (value === this._captureRenderTime) {
  85102. return;
  85103. }
  85104. this._captureRenderTime = value;
  85105. if (value) {
  85106. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  85107. _this._renderTime.beginMonitoring();
  85108. BABYLON.Tools.StartPerformanceCounter("Main render");
  85109. });
  85110. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  85111. _this._renderTime.endMonitoring(false);
  85112. BABYLON.Tools.EndPerformanceCounter("Main render");
  85113. });
  85114. }
  85115. else {
  85116. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  85117. this._onBeforeDrawPhaseObserver = null;
  85118. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  85119. this._onAfterDrawPhaseObserver = null;
  85120. }
  85121. },
  85122. enumerable: true,
  85123. configurable: true
  85124. });
  85125. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  85126. /**
  85127. * Gets the perf counter used for draw calls
  85128. */
  85129. get: function () {
  85130. return this.scene.getEngine()._drawCalls;
  85131. },
  85132. enumerable: true,
  85133. configurable: true
  85134. });
  85135. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  85136. /**
  85137. * Gets the perf counter used for texture collisions
  85138. */
  85139. get: function () {
  85140. return this.scene.getEngine()._textureCollisions;
  85141. },
  85142. enumerable: true,
  85143. configurable: true
  85144. });
  85145. SceneInstrumentation.prototype.dispose = function () {
  85146. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  85147. this._onAfterRenderObserver = null;
  85148. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  85149. this._onBeforeActiveMeshesEvaluationObserver = null;
  85150. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  85151. this._onAfterActiveMeshesEvaluationObserver = null;
  85152. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  85153. this._onBeforeRenderTargetsRenderObserver = null;
  85154. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  85155. this._onAfterRenderTargetsRenderObserver = null;
  85156. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  85157. this._onBeforeAnimationsObserver = null;
  85158. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  85159. this._onBeforeParticlesRenderingObserver = null;
  85160. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  85161. this._onAfterParticlesRenderingObserver = null;
  85162. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  85163. this._onBeforeSpritesRenderingObserver = null;
  85164. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  85165. this._onAfterSpritesRenderingObserver = null;
  85166. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  85167. this._onBeforeDrawPhaseObserver = null;
  85168. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  85169. this._onAfterDrawPhaseObserver = null;
  85170. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  85171. this._onBeforePhysicsObserver = null;
  85172. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  85173. this._onAfterPhysicsObserver = null;
  85174. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  85175. this._onAfterAnimationsObserver = null;
  85176. this.scene = null;
  85177. };
  85178. return SceneInstrumentation;
  85179. }());
  85180. BABYLON.SceneInstrumentation = SceneInstrumentation;
  85181. })(BABYLON || (BABYLON = {}));
  85182. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  85183. var BABYLON;
  85184. (function (BABYLON) {
  85185. var _TimeToken = /** @class */ (function () {
  85186. function _TimeToken() {
  85187. this._timeElapsedQueryEnded = false;
  85188. }
  85189. return _TimeToken;
  85190. }());
  85191. BABYLON._TimeToken = _TimeToken;
  85192. })(BABYLON || (BABYLON = {}));
  85193. //# sourceMappingURL=babylon.timeToken.js.map
  85194. var BABYLON;
  85195. (function (BABYLON) {
  85196. /**
  85197. * Background material defines definition.
  85198. * @ignore Mainly internal Use
  85199. */
  85200. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  85201. __extends(BackgroundMaterialDefines, _super);
  85202. /**
  85203. * Constructor of the defines.
  85204. */
  85205. function BackgroundMaterialDefines() {
  85206. var _this = _super.call(this) || this;
  85207. /**
  85208. * True if the diffuse texture is in use.
  85209. */
  85210. _this.DIFFUSE = false;
  85211. /**
  85212. * The direct UV channel to use.
  85213. */
  85214. _this.DIFFUSEDIRECTUV = 0;
  85215. /**
  85216. * True if the diffuse texture is in gamma space.
  85217. */
  85218. _this.GAMMADIFFUSE = false;
  85219. /**
  85220. * True if the diffuse texture has opacity in the alpha channel.
  85221. */
  85222. _this.DIFFUSEHASALPHA = false;
  85223. /**
  85224. * True if you want the material to fade to transparent at grazing angle.
  85225. */
  85226. _this.OPACITYFRESNEL = false;
  85227. /**
  85228. * True if an extra blur needs to be added in the reflection.
  85229. */
  85230. _this.REFLECTIONBLUR = false;
  85231. /**
  85232. * True if you want the material to fade to reflection at grazing angle.
  85233. */
  85234. _this.REFLECTIONFRESNEL = false;
  85235. /**
  85236. * True if you want the material to falloff as far as you move away from the scene center.
  85237. */
  85238. _this.REFLECTIONFALLOFF = false;
  85239. /**
  85240. * False if the current Webgl implementation does not support the texture lod extension.
  85241. */
  85242. _this.TEXTURELODSUPPORT = false;
  85243. /**
  85244. * True to ensure the data are premultiplied.
  85245. */
  85246. _this.PREMULTIPLYALPHA = false;
  85247. /**
  85248. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  85249. */
  85250. _this.USERGBCOLOR = false;
  85251. /**
  85252. * True to add noise in order to reduce the banding effect.
  85253. */
  85254. _this.NOISE = false;
  85255. // Image Processing Configuration.
  85256. _this.IMAGEPROCESSING = false;
  85257. _this.VIGNETTE = false;
  85258. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  85259. _this.VIGNETTEBLENDMODEOPAQUE = false;
  85260. _this.TONEMAPPING = false;
  85261. _this.CONTRAST = false;
  85262. _this.COLORCURVES = false;
  85263. _this.COLORGRADING = false;
  85264. _this.COLORGRADING3D = false;
  85265. _this.SAMPLER3DGREENDEPTH = false;
  85266. _this.SAMPLER3DBGRMAP = false;
  85267. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  85268. _this.EXPOSURE = false;
  85269. // Reflection.
  85270. _this.REFLECTION = false;
  85271. _this.REFLECTIONMAP_3D = false;
  85272. _this.REFLECTIONMAP_SPHERICAL = false;
  85273. _this.REFLECTIONMAP_PLANAR = false;
  85274. _this.REFLECTIONMAP_CUBIC = false;
  85275. _this.REFLECTIONMAP_PROJECTION = false;
  85276. _this.REFLECTIONMAP_SKYBOX = false;
  85277. _this.REFLECTIONMAP_EXPLICIT = false;
  85278. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  85279. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  85280. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  85281. _this.INVERTCUBICMAP = false;
  85282. _this.REFLECTIONMAP_OPPOSITEZ = false;
  85283. _this.LODINREFLECTIONALPHA = false;
  85284. _this.GAMMAREFLECTION = false;
  85285. // Default BJS.
  85286. _this.MAINUV1 = false;
  85287. _this.MAINUV2 = false;
  85288. _this.UV1 = false;
  85289. _this.UV2 = false;
  85290. _this.CLIPPLANE = false;
  85291. _this.POINTSIZE = false;
  85292. _this.FOG = false;
  85293. _this.NORMAL = false;
  85294. _this.NUM_BONE_INFLUENCERS = 0;
  85295. _this.BonesPerMesh = 0;
  85296. _this.INSTANCES = false;
  85297. _this.SHADOWFLOAT = false;
  85298. _this.rebuild();
  85299. return _this;
  85300. }
  85301. return BackgroundMaterialDefines;
  85302. }(BABYLON.MaterialDefines));
  85303. /**
  85304. * Background material used to create an efficient environement around your scene.
  85305. */
  85306. var BackgroundMaterial = /** @class */ (function (_super) {
  85307. __extends(BackgroundMaterial, _super);
  85308. /**
  85309. * Instantiates a Background Material in the given scene
  85310. * @param name The friendly name of the material
  85311. * @param scene The scene to add the material to
  85312. */
  85313. function BackgroundMaterial(name, scene) {
  85314. var _this = _super.call(this, name, scene) || this;
  85315. /**
  85316. * Key light Color (multiply against the R channel of the environement texture)
  85317. */
  85318. _this.primaryColor = BABYLON.Color3.White();
  85319. /**
  85320. * Key light Level (allowing HDR output of the background)
  85321. */
  85322. _this.primaryLevel = 1;
  85323. /**
  85324. * Secondary light Color (multiply against the G channel of the environement texture)
  85325. */
  85326. _this.secondaryColor = BABYLON.Color3.Gray();
  85327. /**
  85328. * Secondary light Level (allowing HDR output of the background)
  85329. */
  85330. _this.secondaryLevel = 1;
  85331. /**
  85332. * Tertiary light Color (multiply against the B channel of the environement texture)
  85333. */
  85334. _this.tertiaryColor = BABYLON.Color3.Black();
  85335. /**
  85336. * Tertiary light Level (allowing HDR output of the background)
  85337. */
  85338. _this.tertiaryLevel = 1;
  85339. /**
  85340. * Reflection Texture used in the material.
  85341. * Should be author in a specific way for the best result (refer to the documentation).
  85342. */
  85343. _this.reflectionTexture = null;
  85344. /**
  85345. * Reflection Texture level of blur.
  85346. *
  85347. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  85348. * texture twice.
  85349. */
  85350. _this.reflectionBlur = 0;
  85351. /**
  85352. * Diffuse Texture used in the material.
  85353. * Should be author in a specific way for the best result (refer to the documentation).
  85354. */
  85355. _this.diffuseTexture = null;
  85356. _this._shadowLights = null;
  85357. /**
  85358. * Specify the list of lights casting shadow on the material.
  85359. * All scene shadow lights will be included if null.
  85360. */
  85361. _this.shadowLights = null;
  85362. /**
  85363. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  85364. * soft lighting on the background.
  85365. */
  85366. _this.shadowBlurScale = 1;
  85367. /**
  85368. * Helps adjusting the shadow to a softer level if required.
  85369. * 0 means black shadows and 1 means no shadows.
  85370. */
  85371. _this.shadowLevel = 0;
  85372. /**
  85373. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  85374. * It is usually zero but might be interesting to modify according to your setup.
  85375. */
  85376. _this.sceneCenter = BABYLON.Vector3.Zero();
  85377. /**
  85378. * This helps specifying that the material is falling off to the sky box at grazing angle.
  85379. * This helps ensuring a nice transition when the camera goes under the ground.
  85380. */
  85381. _this.opacityFresnel = true;
  85382. /**
  85383. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  85384. * This helps adding a mirror texture on the ground.
  85385. */
  85386. _this.reflectionFresnel = false;
  85387. /**
  85388. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  85389. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  85390. */
  85391. _this.reflectionFalloffDistance = 0.0;
  85392. /**
  85393. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  85394. */
  85395. _this.reflectionAmount = 1.0;
  85396. /**
  85397. * This specifies the weight of the reflection at grazing angle.
  85398. */
  85399. _this.reflectionReflectance0 = 0.05;
  85400. /**
  85401. * This specifies the weight of the reflection at a perpendicular point of view.
  85402. */
  85403. _this.reflectionReflectance90 = 0.5;
  85404. /**
  85405. * Helps to directly use the maps channels instead of their level.
  85406. */
  85407. _this.useRGBColor = true;
  85408. /**
  85409. * This helps reducing the banding effect that could occur on the background.
  85410. */
  85411. _this.enableNoise = false;
  85412. _this._maxSimultaneousLights = 4;
  85413. /**
  85414. * Number of Simultaneous lights allowed on the material.
  85415. */
  85416. _this.maxSimultaneousLights = 4;
  85417. /**
  85418. * Keep track of the image processing observer to allow dispose and replace.
  85419. */
  85420. _this._imageProcessingObserver = null;
  85421. // Temp values kept as cache in the material.
  85422. _this._renderTargets = new BABYLON.SmartArray(16);
  85423. _this._reflectionControls = BABYLON.Vector4.Zero();
  85424. // Setup the default processing configuration to the scene.
  85425. _this._attachImageProcessingConfiguration(null);
  85426. _this.getRenderTargetTextures = function () {
  85427. _this._renderTargets.reset();
  85428. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  85429. _this._renderTargets.push(_this._diffuseTexture);
  85430. }
  85431. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  85432. _this._renderTargets.push(_this._reflectionTexture);
  85433. }
  85434. return _this._renderTargets;
  85435. };
  85436. return _this;
  85437. }
  85438. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  85439. /**
  85440. * Sets the reflection reflectance fresnel values according to the default standard
  85441. * empirically know to work well :-)
  85442. */
  85443. set: function (value) {
  85444. var reflectionWeight = value;
  85445. if (reflectionWeight < 0.5) {
  85446. reflectionWeight = reflectionWeight * 2.0;
  85447. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  85448. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  85449. }
  85450. else {
  85451. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  85452. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  85453. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  85454. }
  85455. },
  85456. enumerable: true,
  85457. configurable: true
  85458. });
  85459. /**
  85460. * Attaches a new image processing configuration to the PBR Material.
  85461. * @param configuration (if null the scene configuration will be use)
  85462. */
  85463. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  85464. var _this = this;
  85465. if (configuration === this._imageProcessingConfiguration) {
  85466. return;
  85467. }
  85468. // Detaches observer.
  85469. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  85470. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  85471. }
  85472. // Pick the scene configuration if needed.
  85473. if (!configuration) {
  85474. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  85475. }
  85476. else {
  85477. this._imageProcessingConfiguration = configuration;
  85478. }
  85479. // Attaches observer.
  85480. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  85481. _this._markAllSubMeshesAsImageProcessingDirty();
  85482. });
  85483. };
  85484. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  85485. /**
  85486. * Gets the image processing configuration used either in this material.
  85487. */
  85488. get: function () {
  85489. return this._imageProcessingConfiguration;
  85490. },
  85491. /**
  85492. * Sets the Default image processing configuration used either in the this material.
  85493. *
  85494. * If sets to null, the scene one is in use.
  85495. */
  85496. set: function (value) {
  85497. this._attachImageProcessingConfiguration(value);
  85498. // Ensure the effect will be rebuilt.
  85499. this._markAllSubMeshesAsTexturesDirty();
  85500. },
  85501. enumerable: true,
  85502. configurable: true
  85503. });
  85504. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  85505. /**
  85506. * Gets wether the color curves effect is enabled.
  85507. */
  85508. get: function () {
  85509. return this.imageProcessingConfiguration.colorCurvesEnabled;
  85510. },
  85511. /**
  85512. * Sets wether the color curves effect is enabled.
  85513. */
  85514. set: function (value) {
  85515. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  85516. },
  85517. enumerable: true,
  85518. configurable: true
  85519. });
  85520. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  85521. /**
  85522. * Gets wether the color grading effect is enabled.
  85523. */
  85524. get: function () {
  85525. return this.imageProcessingConfiguration.colorGradingEnabled;
  85526. },
  85527. /**
  85528. * Gets wether the color grading effect is enabled.
  85529. */
  85530. set: function (value) {
  85531. this.imageProcessingConfiguration.colorGradingEnabled = value;
  85532. },
  85533. enumerable: true,
  85534. configurable: true
  85535. });
  85536. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  85537. /**
  85538. * Gets wether tonemapping is enabled or not.
  85539. */
  85540. get: function () {
  85541. return this._imageProcessingConfiguration.toneMappingEnabled;
  85542. },
  85543. /**
  85544. * Sets wether tonemapping is enabled or not
  85545. */
  85546. set: function (value) {
  85547. this._imageProcessingConfiguration.toneMappingEnabled = value;
  85548. },
  85549. enumerable: true,
  85550. configurable: true
  85551. });
  85552. ;
  85553. ;
  85554. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  85555. /**
  85556. * The camera exposure used on this material.
  85557. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  85558. * This corresponds to a photographic exposure.
  85559. */
  85560. get: function () {
  85561. return this._imageProcessingConfiguration.exposure;
  85562. },
  85563. /**
  85564. * The camera exposure used on this material.
  85565. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  85566. * This corresponds to a photographic exposure.
  85567. */
  85568. set: function (value) {
  85569. this._imageProcessingConfiguration.exposure = value;
  85570. },
  85571. enumerable: true,
  85572. configurable: true
  85573. });
  85574. ;
  85575. ;
  85576. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  85577. /**
  85578. * Gets The camera contrast used on this material.
  85579. */
  85580. get: function () {
  85581. return this._imageProcessingConfiguration.contrast;
  85582. },
  85583. /**
  85584. * Sets The camera contrast used on this material.
  85585. */
  85586. set: function (value) {
  85587. this._imageProcessingConfiguration.contrast = value;
  85588. },
  85589. enumerable: true,
  85590. configurable: true
  85591. });
  85592. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  85593. /**
  85594. * Gets the Color Grading 2D Lookup Texture.
  85595. */
  85596. get: function () {
  85597. return this._imageProcessingConfiguration.colorGradingTexture;
  85598. },
  85599. /**
  85600. * Sets the Color Grading 2D Lookup Texture.
  85601. */
  85602. set: function (value) {
  85603. this.imageProcessingConfiguration.colorGradingTexture = value;
  85604. },
  85605. enumerable: true,
  85606. configurable: true
  85607. });
  85608. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  85609. /**
  85610. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  85611. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  85612. * 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;
  85613. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  85614. */
  85615. get: function () {
  85616. return this.imageProcessingConfiguration.colorCurves;
  85617. },
  85618. /**
  85619. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  85620. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  85621. * 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;
  85622. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  85623. */
  85624. set: function (value) {
  85625. this.imageProcessingConfiguration.colorCurves = value;
  85626. },
  85627. enumerable: true,
  85628. configurable: true
  85629. });
  85630. /**
  85631. * The entire material has been created in order to prevent overdraw.
  85632. * @returns false
  85633. */
  85634. BackgroundMaterial.prototype.needAlphaTesting = function () {
  85635. return true;
  85636. };
  85637. /**
  85638. * The entire material has been created in order to prevent overdraw.
  85639. * @returns true if blending is enable
  85640. */
  85641. BackgroundMaterial.prototype.needAlphaBlending = function () {
  85642. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  85643. };
  85644. /**
  85645. * Checks wether the material is ready to be rendered for a given mesh.
  85646. * @param mesh The mesh to render
  85647. * @param subMesh The submesh to check against
  85648. * @param useInstances Specify wether or not the material is used with instances
  85649. * @returns true if all the dependencies are ready (Textures, Effects...)
  85650. */
  85651. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  85652. var _this = this;
  85653. if (useInstances === void 0) { useInstances = false; }
  85654. if (subMesh.effect && this.isFrozen) {
  85655. if (this._wasPreviouslyReady) {
  85656. return true;
  85657. }
  85658. }
  85659. if (!subMesh._materialDefines) {
  85660. subMesh._materialDefines = new BackgroundMaterialDefines();
  85661. }
  85662. var scene = this.getScene();
  85663. var defines = subMesh._materialDefines;
  85664. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  85665. if (defines._renderId === scene.getRenderId()) {
  85666. return true;
  85667. }
  85668. }
  85669. var engine = scene.getEngine();
  85670. // Lights
  85671. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  85672. defines._needNormals = true;
  85673. // Textures
  85674. if (defines._areTexturesDirty) {
  85675. defines._needUVs = false;
  85676. if (scene.texturesEnabled) {
  85677. if (scene.getEngine().getCaps().textureLOD) {
  85678. defines.TEXTURELODSUPPORT = true;
  85679. }
  85680. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  85681. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  85682. return false;
  85683. }
  85684. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  85685. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  85686. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  85687. defines.OPACITYFRESNEL = this._opacityFresnel;
  85688. }
  85689. else {
  85690. defines.DIFFUSE = false;
  85691. defines.DIFFUSEHASALPHA = false;
  85692. defines.GAMMADIFFUSE = false;
  85693. defines.OPACITYFRESNEL = false;
  85694. }
  85695. var reflectionTexture = this._reflectionTexture;
  85696. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  85697. if (!reflectionTexture.isReadyOrNotBlocking()) {
  85698. return false;
  85699. }
  85700. defines.REFLECTION = true;
  85701. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  85702. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  85703. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  85704. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  85705. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  85706. defines.INVERTCUBICMAP = true;
  85707. }
  85708. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  85709. switch (reflectionTexture.coordinatesMode) {
  85710. case BABYLON.Texture.CUBIC_MODE:
  85711. case BABYLON.Texture.INVCUBIC_MODE:
  85712. defines.REFLECTIONMAP_CUBIC = true;
  85713. break;
  85714. case BABYLON.Texture.EXPLICIT_MODE:
  85715. defines.REFLECTIONMAP_EXPLICIT = true;
  85716. break;
  85717. case BABYLON.Texture.PLANAR_MODE:
  85718. defines.REFLECTIONMAP_PLANAR = true;
  85719. break;
  85720. case BABYLON.Texture.PROJECTION_MODE:
  85721. defines.REFLECTIONMAP_PROJECTION = true;
  85722. break;
  85723. case BABYLON.Texture.SKYBOX_MODE:
  85724. defines.REFLECTIONMAP_SKYBOX = true;
  85725. break;
  85726. case BABYLON.Texture.SPHERICAL_MODE:
  85727. defines.REFLECTIONMAP_SPHERICAL = true;
  85728. break;
  85729. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  85730. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  85731. break;
  85732. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  85733. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  85734. break;
  85735. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  85736. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  85737. break;
  85738. }
  85739. if (this.reflectionFresnel) {
  85740. defines.REFLECTIONFRESNEL = true;
  85741. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  85742. this._reflectionControls.x = this.reflectionAmount;
  85743. this._reflectionControls.y = this.reflectionReflectance0;
  85744. this._reflectionControls.z = this.reflectionReflectance90;
  85745. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  85746. }
  85747. else {
  85748. defines.REFLECTIONFRESNEL = false;
  85749. defines.REFLECTIONFALLOFF = false;
  85750. }
  85751. }
  85752. else {
  85753. defines.REFLECTION = false;
  85754. defines.REFLECTIONFALLOFF = false;
  85755. defines.REFLECTIONBLUR = false;
  85756. defines.REFLECTIONMAP_3D = false;
  85757. defines.REFLECTIONMAP_SPHERICAL = false;
  85758. defines.REFLECTIONMAP_PLANAR = false;
  85759. defines.REFLECTIONMAP_CUBIC = false;
  85760. defines.REFLECTIONMAP_PROJECTION = false;
  85761. defines.REFLECTIONMAP_SKYBOX = false;
  85762. defines.REFLECTIONMAP_EXPLICIT = false;
  85763. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  85764. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  85765. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  85766. defines.INVERTCUBICMAP = false;
  85767. defines.REFLECTIONMAP_OPPOSITEZ = false;
  85768. defines.LODINREFLECTIONALPHA = false;
  85769. defines.GAMMAREFLECTION = false;
  85770. }
  85771. }
  85772. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  85773. defines.USERGBCOLOR = this._useRGBColor;
  85774. defines.NOISE = this._enableNoise;
  85775. }
  85776. if (defines._areImageProcessingDirty) {
  85777. if (!this._imageProcessingConfiguration.isReady()) {
  85778. return false;
  85779. }
  85780. this._imageProcessingConfiguration.prepareDefines(defines);
  85781. }
  85782. // Misc.
  85783. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  85784. // Values that need to be evaluated on every frame
  85785. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  85786. // Attribs
  85787. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  85788. if (mesh) {
  85789. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  85790. mesh.createNormals(true);
  85791. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  85792. }
  85793. }
  85794. }
  85795. // Get correct effect
  85796. if (defines.isDirty) {
  85797. defines.markAsProcessed();
  85798. scene.resetCachedMaterial();
  85799. // Fallbacks
  85800. var fallbacks = new BABYLON.EffectFallbacks();
  85801. if (defines.FOG) {
  85802. fallbacks.addFallback(0, "FOG");
  85803. }
  85804. if (defines.POINTSIZE) {
  85805. fallbacks.addFallback(1, "POINTSIZE");
  85806. }
  85807. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  85808. if (defines.NUM_BONE_INFLUENCERS > 0) {
  85809. fallbacks.addCPUSkinningFallback(0, mesh);
  85810. }
  85811. //Attributes
  85812. var attribs = [BABYLON.VertexBuffer.PositionKind];
  85813. if (defines.NORMAL) {
  85814. attribs.push(BABYLON.VertexBuffer.NormalKind);
  85815. }
  85816. if (defines.UV1) {
  85817. attribs.push(BABYLON.VertexBuffer.UVKind);
  85818. }
  85819. if (defines.UV2) {
  85820. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85821. }
  85822. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  85823. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  85824. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  85825. "vFogInfos", "vFogColor", "pointSize",
  85826. "vClipPlane", "mBones",
  85827. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  85828. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  85829. "shadowLevel", "alpha",
  85830. "vBackgroundCenter", "vReflectionControl",
  85831. "vDiffuseInfos", "diffuseMatrix",
  85832. ];
  85833. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  85834. var uniformBuffers = ["Material", "Scene"];
  85835. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  85836. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  85837. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  85838. uniformsNames: uniforms,
  85839. uniformBuffersNames: uniformBuffers,
  85840. samplers: samplers,
  85841. defines: defines,
  85842. maxSimultaneousLights: this._maxSimultaneousLights
  85843. });
  85844. var onCompiled = function (effect) {
  85845. if (_this.onCompiled) {
  85846. _this.onCompiled(effect);
  85847. }
  85848. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  85849. };
  85850. var join = defines.toString();
  85851. subMesh.setEffect(scene.getEngine().createEffect("background", {
  85852. attributes: attribs,
  85853. uniformsNames: uniforms,
  85854. uniformBuffersNames: uniformBuffers,
  85855. samplers: samplers,
  85856. defines: join,
  85857. fallbacks: fallbacks,
  85858. onCompiled: onCompiled,
  85859. onError: this.onError,
  85860. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  85861. }, engine), defines);
  85862. this.buildUniformLayout();
  85863. }
  85864. if (!subMesh.effect || !subMesh.effect.isReady()) {
  85865. return false;
  85866. }
  85867. defines._renderId = scene.getRenderId();
  85868. this._wasPreviouslyReady = true;
  85869. return true;
  85870. };
  85871. /**
  85872. * Build the uniform buffer used in the material.
  85873. */
  85874. BackgroundMaterial.prototype.buildUniformLayout = function () {
  85875. // Order is important !
  85876. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  85877. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  85878. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  85879. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  85880. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  85881. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  85882. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  85883. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  85884. this._uniformBuffer.addUniform("pointSize", 1);
  85885. this._uniformBuffer.addUniform("shadowLevel", 1);
  85886. this._uniformBuffer.addUniform("alpha", 1);
  85887. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  85888. this._uniformBuffer.addUniform("vReflectionControl", 4);
  85889. this._uniformBuffer.create();
  85890. };
  85891. /**
  85892. * Unbind the material.
  85893. */
  85894. BackgroundMaterial.prototype.unbind = function () {
  85895. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  85896. this._uniformBuffer.setTexture("diffuseSampler", null);
  85897. }
  85898. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  85899. this._uniformBuffer.setTexture("reflectionSampler", null);
  85900. }
  85901. _super.prototype.unbind.call(this);
  85902. };
  85903. /**
  85904. * Bind only the world matrix to the material.
  85905. * @param world The world matrix to bind.
  85906. */
  85907. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  85908. this._activeEffect.setMatrix("world", world);
  85909. };
  85910. /**
  85911. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  85912. * @param world The world matrix to bind.
  85913. * @param subMesh The submesh to bind for.
  85914. */
  85915. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  85916. var scene = this.getScene();
  85917. var defines = subMesh._materialDefines;
  85918. if (!defines) {
  85919. return;
  85920. }
  85921. var effect = subMesh.effect;
  85922. if (!effect) {
  85923. return;
  85924. }
  85925. this._activeEffect = effect;
  85926. // Matrices
  85927. this.bindOnlyWorldMatrix(world);
  85928. // Bones
  85929. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  85930. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  85931. if (mustRebind) {
  85932. this._uniformBuffer.bindToEffect(effect, "Material");
  85933. this.bindViewProjection(effect);
  85934. var reflectionTexture = this._reflectionTexture;
  85935. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  85936. // Texture uniforms
  85937. if (scene.texturesEnabled) {
  85938. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  85939. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  85940. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  85941. }
  85942. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  85943. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  85944. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  85945. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  85946. }
  85947. }
  85948. if (this.shadowLevel > 0) {
  85949. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  85950. }
  85951. this._uniformBuffer.updateFloat("alpha", this.alpha);
  85952. // Point size
  85953. if (this.pointsCloud) {
  85954. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  85955. }
  85956. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  85957. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  85958. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  85959. }
  85960. // Textures
  85961. if (scene.texturesEnabled) {
  85962. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  85963. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  85964. }
  85965. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  85966. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  85967. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  85968. }
  85969. else if (!defines.REFLECTIONBLUR) {
  85970. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  85971. }
  85972. else {
  85973. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  85974. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  85975. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  85976. }
  85977. if (defines.REFLECTIONFRESNEL) {
  85978. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  85979. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  85980. }
  85981. }
  85982. }
  85983. // Clip plane
  85984. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  85985. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  85986. }
  85987. if (mustRebind || !this.isFrozen) {
  85988. if (scene.lightsEnabled) {
  85989. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  85990. }
  85991. // View
  85992. this.bindView(effect);
  85993. // Fog
  85994. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  85995. // image processing
  85996. this._imageProcessingConfiguration.bind(this._activeEffect);
  85997. }
  85998. this._uniformBuffer.update();
  85999. this._afterBind(mesh);
  86000. };
  86001. /**
  86002. * Dispose the material.
  86003. * @param forceDisposeEffect Force disposal of the associated effect.
  86004. * @param forceDisposeTextures Force disposal of the associated textures.
  86005. */
  86006. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  86007. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  86008. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  86009. if (forceDisposeTextures) {
  86010. if (this.diffuseTexture) {
  86011. this.diffuseTexture.dispose();
  86012. }
  86013. if (this.reflectionTexture) {
  86014. this.reflectionTexture.dispose();
  86015. }
  86016. }
  86017. this._renderTargets.dispose();
  86018. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  86019. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  86020. }
  86021. _super.prototype.dispose.call(this, forceDisposeEffect);
  86022. };
  86023. /**
  86024. * Clones the material.
  86025. * @param name The cloned name.
  86026. * @returns The cloned material.
  86027. */
  86028. BackgroundMaterial.prototype.clone = function (name) {
  86029. var _this = this;
  86030. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  86031. };
  86032. /**
  86033. * Serializes the current material to its JSON representation.
  86034. * @returns The JSON representation.
  86035. */
  86036. BackgroundMaterial.prototype.serialize = function () {
  86037. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  86038. serializationObject.customType = "BABYLON.BackgroundMaterial";
  86039. return serializationObject;
  86040. };
  86041. /**
  86042. * Gets the class name of the material
  86043. * @returns "BackgroundMaterial"
  86044. */
  86045. BackgroundMaterial.prototype.getClassName = function () {
  86046. return "BackgroundMaterial";
  86047. };
  86048. /**
  86049. * Parse a JSON input to create back a background material.
  86050. * @param source The JSON data to parse
  86051. * @param scene The scene to create the parsed material in
  86052. * @param rootUrl The root url of the assets the material depends upon
  86053. * @returns the instantiated BackgroundMaterial.
  86054. */
  86055. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  86056. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  86057. };
  86058. /**
  86059. * Standard reflectance value at parallel view angle.
  86060. */
  86061. BackgroundMaterial.StandardReflectance0 = 0.05;
  86062. /**
  86063. * Standard reflectance value at grazing angle.
  86064. */
  86065. BackgroundMaterial.StandardReflectance90 = 0.5;
  86066. __decorate([
  86067. BABYLON.serializeAsColor3()
  86068. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  86069. __decorate([
  86070. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  86071. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  86072. __decorate([
  86073. BABYLON.serialize()
  86074. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  86075. __decorate([
  86076. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  86077. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  86078. __decorate([
  86079. BABYLON.serializeAsColor3()
  86080. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  86081. __decorate([
  86082. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  86083. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  86084. __decorate([
  86085. BABYLON.serialize()
  86086. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  86087. __decorate([
  86088. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  86089. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  86090. __decorate([
  86091. BABYLON.serializeAsColor3()
  86092. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  86093. __decorate([
  86094. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  86095. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  86096. __decorate([
  86097. BABYLON.serialize()
  86098. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  86099. __decorate([
  86100. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  86101. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  86102. __decorate([
  86103. BABYLON.serializeAsTexture()
  86104. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  86105. __decorate([
  86106. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86107. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  86108. __decorate([
  86109. BABYLON.serialize()
  86110. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  86111. __decorate([
  86112. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86113. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  86114. __decorate([
  86115. BABYLON.serializeAsTexture()
  86116. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  86117. __decorate([
  86118. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86119. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  86120. __decorate([
  86121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86122. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  86123. __decorate([
  86124. BABYLON.serialize()
  86125. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  86126. __decorate([
  86127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86128. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  86129. __decorate([
  86130. BABYLON.serialize()
  86131. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  86132. __decorate([
  86133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86134. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  86135. __decorate([
  86136. BABYLON.serializeAsVector3()
  86137. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  86138. __decorate([
  86139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86140. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  86141. __decorate([
  86142. BABYLON.serialize()
  86143. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  86144. __decorate([
  86145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86146. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  86147. __decorate([
  86148. BABYLON.serialize()
  86149. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  86150. __decorate([
  86151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86152. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  86153. __decorate([
  86154. BABYLON.serialize()
  86155. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  86156. __decorate([
  86157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86158. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  86159. __decorate([
  86160. BABYLON.serialize()
  86161. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  86162. __decorate([
  86163. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86164. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  86165. __decorate([
  86166. BABYLON.serialize()
  86167. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  86168. __decorate([
  86169. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86170. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  86171. __decorate([
  86172. BABYLON.serialize()
  86173. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  86174. __decorate([
  86175. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86176. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  86177. __decorate([
  86178. BABYLON.serialize()
  86179. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  86180. __decorate([
  86181. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86182. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  86183. __decorate([
  86184. BABYLON.serialize()
  86185. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  86186. __decorate([
  86187. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86188. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  86189. __decorate([
  86190. BABYLON.serialize()
  86191. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  86192. __decorate([
  86193. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  86194. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  86195. __decorate([
  86196. BABYLON.serializeAsImageProcessingConfiguration()
  86197. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  86198. return BackgroundMaterial;
  86199. }(BABYLON.PushMaterial));
  86200. BABYLON.BackgroundMaterial = BackgroundMaterial;
  86201. })(BABYLON || (BABYLON = {}));
  86202. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  86203. var __assign = (this && this.__assign) || Object.assign || function(t) {
  86204. for (var s, i = 1, n = arguments.length; i < n; i++) {
  86205. s = arguments[i];
  86206. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  86207. t[p] = s[p];
  86208. }
  86209. return t;
  86210. };
  86211. var BABYLON;
  86212. (function (BABYLON) {
  86213. /**
  86214. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  86215. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  86216. * It also helps with the default setup of your imageProcessing configuration.
  86217. */
  86218. var EnvironmentHelper = /** @class */ (function () {
  86219. /**
  86220. * constructor
  86221. * @param options
  86222. * @param scene The scene to add the material to
  86223. */
  86224. function EnvironmentHelper(options, scene) {
  86225. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  86226. this._scene = scene;
  86227. this._setupBackground();
  86228. this._setupImageProcessing();
  86229. }
  86230. /**
  86231. * Creates the default options for the helper.
  86232. */
  86233. EnvironmentHelper._getDefaultOptions = function () {
  86234. return {
  86235. createGround: true,
  86236. groundSize: 15,
  86237. groundTexture: this._groundTextureCDNUrl,
  86238. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  86239. groundOpacity: 0.9,
  86240. enableGroundShadow: true,
  86241. groundShadowLevel: 0.5,
  86242. enableGroundMirror: false,
  86243. groundMirrorSizeRatio: 0.3,
  86244. groundMirrorBlurKernel: 64,
  86245. groundMirrorAmount: 1,
  86246. groundMirrorFresnelWeight: 1,
  86247. groundMirrorFallOffDistance: 0,
  86248. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  86249. groundYBias: 0.00001,
  86250. createSkybox: true,
  86251. skyboxSize: 20,
  86252. skyboxTexture: this._skyboxTextureCDNUrl,
  86253. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  86254. backgroundYRotation: 0,
  86255. sizeAuto: true,
  86256. rootPosition: BABYLON.Vector3.Zero(),
  86257. setupImageProcessing: true,
  86258. environmentTexture: this._environmentTextureCDNUrl,
  86259. cameraExposure: 0.8,
  86260. cameraContrast: 1.2,
  86261. toneMappingEnabled: true,
  86262. };
  86263. };
  86264. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  86265. /**
  86266. * Gets the root mesh created by the helper.
  86267. */
  86268. get: function () {
  86269. return this._rootMesh;
  86270. },
  86271. enumerable: true,
  86272. configurable: true
  86273. });
  86274. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  86275. /**
  86276. * Gets the skybox created by the helper.
  86277. */
  86278. get: function () {
  86279. return this._skybox;
  86280. },
  86281. enumerable: true,
  86282. configurable: true
  86283. });
  86284. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  86285. /**
  86286. * Gets the skybox texture created by the helper.
  86287. */
  86288. get: function () {
  86289. return this._skyboxTexture;
  86290. },
  86291. enumerable: true,
  86292. configurable: true
  86293. });
  86294. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  86295. /**
  86296. * Gets the skybox material created by the helper.
  86297. */
  86298. get: function () {
  86299. return this._skyboxMaterial;
  86300. },
  86301. enumerable: true,
  86302. configurable: true
  86303. });
  86304. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  86305. /**
  86306. * Gets the ground mesh created by the helper.
  86307. */
  86308. get: function () {
  86309. return this._ground;
  86310. },
  86311. enumerable: true,
  86312. configurable: true
  86313. });
  86314. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  86315. /**
  86316. * Gets the ground texture created by the helper.
  86317. */
  86318. get: function () {
  86319. return this._groundTexture;
  86320. },
  86321. enumerable: true,
  86322. configurable: true
  86323. });
  86324. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  86325. /**
  86326. * Gets the ground mirror created by the helper.
  86327. */
  86328. get: function () {
  86329. return this._groundMirror;
  86330. },
  86331. enumerable: true,
  86332. configurable: true
  86333. });
  86334. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  86335. /**
  86336. * Gets the ground mirror render list to helps pushing the meshes
  86337. * you wish in the ground reflection.
  86338. */
  86339. get: function () {
  86340. if (this._groundMirror) {
  86341. return this._groundMirror.renderList;
  86342. }
  86343. return null;
  86344. },
  86345. enumerable: true,
  86346. configurable: true
  86347. });
  86348. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  86349. /**
  86350. * Gets the ground material created by the helper.
  86351. */
  86352. get: function () {
  86353. return this._groundMaterial;
  86354. },
  86355. enumerable: true,
  86356. configurable: true
  86357. });
  86358. /**
  86359. * Updates the background according to the new options
  86360. * @param options
  86361. */
  86362. EnvironmentHelper.prototype.updateOptions = function (options) {
  86363. var newOptions = __assign({}, this._options, options);
  86364. if (this._ground && !newOptions.createGround) {
  86365. this._ground.dispose();
  86366. this._ground = null;
  86367. }
  86368. if (this._groundMaterial && !newOptions.createGround) {
  86369. this._groundMaterial.dispose();
  86370. this._groundMaterial = null;
  86371. }
  86372. if (this._groundTexture) {
  86373. if (this._options.groundTexture != newOptions.groundTexture) {
  86374. this._groundTexture.dispose();
  86375. this._groundTexture = null;
  86376. }
  86377. }
  86378. if (this._skybox && !newOptions.createSkybox) {
  86379. this._skybox.dispose();
  86380. this._skybox = null;
  86381. }
  86382. if (this._skyboxMaterial && !newOptions.createSkybox) {
  86383. this._skyboxMaterial.dispose();
  86384. this._skyboxMaterial = null;
  86385. }
  86386. if (this._skyboxTexture) {
  86387. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  86388. this._skyboxTexture.dispose();
  86389. this._skyboxTexture = null;
  86390. }
  86391. }
  86392. if (this._groundMirror && !newOptions.enableGroundMirror) {
  86393. this._groundMirror.dispose();
  86394. this._groundMirror = null;
  86395. }
  86396. if (this._scene.environmentTexture) {
  86397. if (this._options.environmentTexture != newOptions.environmentTexture) {
  86398. this._scene.environmentTexture.dispose();
  86399. }
  86400. }
  86401. this._options = newOptions;
  86402. this._setupBackground();
  86403. this._setupImageProcessing();
  86404. };
  86405. /**
  86406. * Sets the primary color of all the available elements.
  86407. * @param color
  86408. */
  86409. EnvironmentHelper.prototype.setMainColor = function (color) {
  86410. if (this.groundMaterial) {
  86411. this.groundMaterial.primaryColor = color;
  86412. }
  86413. if (this.skyboxMaterial) {
  86414. this.skyboxMaterial.primaryColor = color;
  86415. }
  86416. if (this.groundMirror) {
  86417. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  86418. }
  86419. };
  86420. /**
  86421. * Setup the image processing according to the specified options.
  86422. */
  86423. EnvironmentHelper.prototype._setupImageProcessing = function () {
  86424. if (this._options.setupImageProcessing) {
  86425. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  86426. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  86427. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  86428. this._setupEnvironmentTexture();
  86429. }
  86430. };
  86431. /**
  86432. * Setup the environment texture according to the specified options.
  86433. */
  86434. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  86435. if (this._scene.environmentTexture) {
  86436. return;
  86437. }
  86438. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  86439. this._scene.environmentTexture = this._options.environmentTexture;
  86440. return;
  86441. }
  86442. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  86443. this._scene.environmentTexture = environmentTexture;
  86444. };
  86445. /**
  86446. * Setup the background according to the specified options.
  86447. */
  86448. EnvironmentHelper.prototype._setupBackground = function () {
  86449. if (!this._rootMesh) {
  86450. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  86451. }
  86452. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  86453. var sceneSize = this._getSceneSize();
  86454. if (this._options.createGround) {
  86455. this._setupGround(sceneSize);
  86456. this._setupGroundMaterial();
  86457. this._setupGroundDiffuseTexture();
  86458. if (this._options.enableGroundMirror) {
  86459. this._setupGroundMirrorTexture(sceneSize);
  86460. }
  86461. this._setupMirrorInGroundMaterial();
  86462. }
  86463. if (this._options.createSkybox) {
  86464. this._setupSkybox(sceneSize);
  86465. this._setupSkyboxMaterial();
  86466. this._setupSkyboxReflectionTexture();
  86467. }
  86468. this._rootMesh.position.x = sceneSize.rootPosition.x;
  86469. this._rootMesh.position.z = sceneSize.rootPosition.z;
  86470. this._rootMesh.position.y = sceneSize.rootPosition.y;
  86471. };
  86472. /**
  86473. * Get the scene sizes according to the setup.
  86474. */
  86475. EnvironmentHelper.prototype._getSceneSize = function () {
  86476. var groundSize = this._options.groundSize;
  86477. var skyboxSize = this._options.skyboxSize;
  86478. var rootPosition = this._options.rootPosition;
  86479. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  86480. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  86481. }
  86482. var sceneExtends = this._scene.getWorldExtends();
  86483. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  86484. if (this._options.sizeAuto) {
  86485. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  86486. this._scene.activeCamera.upperRadiusLimit) {
  86487. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  86488. skyboxSize = groundSize;
  86489. }
  86490. var sceneDiagonalLenght = sceneDiagonal.length();
  86491. if (sceneDiagonalLenght > groundSize) {
  86492. groundSize = sceneDiagonalLenght * 2;
  86493. skyboxSize = groundSize;
  86494. }
  86495. // 10 % bigger.
  86496. groundSize *= 1.1;
  86497. skyboxSize *= 1.5;
  86498. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  86499. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  86500. }
  86501. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  86502. };
  86503. /**
  86504. * Setup the ground according to the specified options.
  86505. */
  86506. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  86507. var _this = this;
  86508. if (!this._ground) {
  86509. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  86510. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  86511. this._ground.parent = this._rootMesh;
  86512. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  86513. }
  86514. this._ground.receiveShadows = this._options.enableGroundShadow;
  86515. };
  86516. /**
  86517. * Setup the ground material according to the specified options.
  86518. */
  86519. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  86520. if (!this._groundMaterial) {
  86521. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  86522. }
  86523. this._groundMaterial.alpha = this._options.groundOpacity;
  86524. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  86525. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  86526. this._groundMaterial.primaryLevel = 1;
  86527. this._groundMaterial.primaryColor = this._options.groundColor;
  86528. this._groundMaterial.secondaryLevel = 0;
  86529. this._groundMaterial.tertiaryLevel = 0;
  86530. this._groundMaterial.useRGBColor = false;
  86531. this._groundMaterial.enableNoise = true;
  86532. if (this._ground) {
  86533. this._ground.material = this._groundMaterial;
  86534. }
  86535. };
  86536. /**
  86537. * Setup the ground diffuse texture according to the specified options.
  86538. */
  86539. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  86540. if (!this._groundMaterial) {
  86541. return;
  86542. }
  86543. if (this._groundTexture) {
  86544. return;
  86545. }
  86546. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  86547. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  86548. return;
  86549. }
  86550. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  86551. diffuseTexture.gammaSpace = false;
  86552. diffuseTexture.hasAlpha = true;
  86553. this._groundMaterial.diffuseTexture = diffuseTexture;
  86554. };
  86555. /**
  86556. * Setup the ground mirror texture according to the specified options.
  86557. */
  86558. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  86559. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86560. if (!this._groundMirror) {
  86561. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  86562. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  86563. this._groundMirror.anisotropicFilteringLevel = 1;
  86564. this._groundMirror.wrapU = wrapping;
  86565. this._groundMirror.wrapV = wrapping;
  86566. this._groundMirror.gammaSpace = false;
  86567. if (this._groundMirror.renderList) {
  86568. for (var i = 0; i < this._scene.meshes.length; i++) {
  86569. var mesh = this._scene.meshes[i];
  86570. if (mesh !== this._ground &&
  86571. mesh !== this._skybox &&
  86572. mesh !== this._rootMesh) {
  86573. this._groundMirror.renderList.push(mesh);
  86574. }
  86575. }
  86576. }
  86577. }
  86578. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  86579. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  86580. };
  86581. /**
  86582. * Setup the ground to receive the mirror texture.
  86583. */
  86584. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  86585. if (this._groundMaterial) {
  86586. this._groundMaterial.reflectionTexture = this._groundMirror;
  86587. this._groundMaterial.reflectionFresnel = true;
  86588. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  86589. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  86590. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  86591. }
  86592. };
  86593. /**
  86594. * Setup the skybox according to the specified options.
  86595. */
  86596. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  86597. var _this = this;
  86598. if (!this._skybox) {
  86599. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  86600. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  86601. }
  86602. this._skybox.parent = this._rootMesh;
  86603. };
  86604. /**
  86605. * Setup the skybox material according to the specified options.
  86606. */
  86607. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  86608. if (!this._skybox) {
  86609. return;
  86610. }
  86611. if (!this._skyboxMaterial) {
  86612. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  86613. }
  86614. this._skyboxMaterial.useRGBColor = false;
  86615. this._skyboxMaterial.primaryLevel = 1;
  86616. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  86617. this._skyboxMaterial.secondaryLevel = 0;
  86618. this._skyboxMaterial.tertiaryLevel = 0;
  86619. this._skyboxMaterial.enableNoise = true;
  86620. this._skybox.material = this._skyboxMaterial;
  86621. };
  86622. /**
  86623. * Setup the skybox reflection texture according to the specified options.
  86624. */
  86625. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  86626. if (!this._skyboxMaterial) {
  86627. return;
  86628. }
  86629. if (this._skyboxTexture) {
  86630. return;
  86631. }
  86632. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  86633. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  86634. return;
  86635. }
  86636. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  86637. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  86638. this._skyboxTexture.gammaSpace = false;
  86639. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  86640. };
  86641. /**
  86642. * Dispose all the elements created by the Helper.
  86643. */
  86644. EnvironmentHelper.prototype.dispose = function () {
  86645. if (this._groundMaterial) {
  86646. this._groundMaterial.dispose(true, true);
  86647. }
  86648. if (this._skyboxMaterial) {
  86649. this._skyboxMaterial.dispose(true, true);
  86650. }
  86651. this._rootMesh.dispose(false);
  86652. };
  86653. /**
  86654. * Default ground texture URL.
  86655. */
  86656. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  86657. /**
  86658. * Default skybox texture URL.
  86659. */
  86660. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  86661. /**
  86662. * Default environment texture URL.
  86663. */
  86664. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  86665. return EnvironmentHelper;
  86666. }());
  86667. BABYLON.EnvironmentHelper = EnvironmentHelper;
  86668. })(BABYLON || (BABYLON = {}));
  86669. //# sourceMappingURL=babylon.environmentHelper.js.map
  86670. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,coc,coc,1.0);\n}\n","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec4 blurred=texture2D(textureSampler,vUV);\nvec4 original=texture2D(originalSampler,vUV);\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\ngl_FragColor=mix(original,blurred,coc);\n}\n","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D depthSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb=dither(vPositionW.xy,color.rgb);\n#endif\ngl_FragColor=color;\n}"};
  86671. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  86672. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  86673. var BABYLON;
  86674. (function (BABYLON) {
  86675. var GridMaterialDefines = /** @class */ (function (_super) {
  86676. __extends(GridMaterialDefines, _super);
  86677. function GridMaterialDefines() {
  86678. var _this = _super.call(this) || this;
  86679. _this.TRANSPARENT = false;
  86680. _this.FOG = false;
  86681. _this.PREMULTIPLYALPHA = false;
  86682. _this.rebuild();
  86683. return _this;
  86684. }
  86685. return GridMaterialDefines;
  86686. }(BABYLON.MaterialDefines));
  86687. /**
  86688. * The grid materials allows you to wrap any shape with a grid.
  86689. * Colors are customizable.
  86690. */
  86691. var GridMaterial = /** @class */ (function (_super) {
  86692. __extends(GridMaterial, _super);
  86693. /**
  86694. * constructor
  86695. * @param name The name given to the material in order to identify it afterwards.
  86696. * @param scene The scene the material is used in.
  86697. */
  86698. function GridMaterial(name, scene) {
  86699. var _this = _super.call(this, name, scene) || this;
  86700. /**
  86701. * Main color of the grid (e.g. between lines)
  86702. */
  86703. _this.mainColor = BABYLON.Color3.Black();
  86704. /**
  86705. * Color of the grid lines.
  86706. */
  86707. _this.lineColor = BABYLON.Color3.Teal();
  86708. /**
  86709. * The scale of the grid compared to unit.
  86710. */
  86711. _this.gridRatio = 1.0;
  86712. /**
  86713. * Allows setting an offset for the grid lines.
  86714. */
  86715. _this.gridOffset = BABYLON.Vector3.Zero();
  86716. /**
  86717. * The frequency of thicker lines.
  86718. */
  86719. _this.majorUnitFrequency = 10;
  86720. /**
  86721. * The visibility of minor units in the grid.
  86722. */
  86723. _this.minorUnitVisibility = 0.33;
  86724. /**
  86725. * The grid opacity outside of the lines.
  86726. */
  86727. _this.opacity = 1.0;
  86728. /**
  86729. * Determine RBG output is premultiplied by alpha value.
  86730. */
  86731. _this.preMultiplyAlpha = false;
  86732. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  86733. return _this;
  86734. }
  86735. /**
  86736. * Returns wehter or not the grid requires alpha blending.
  86737. */
  86738. GridMaterial.prototype.needAlphaBlending = function () {
  86739. return this.opacity < 1.0;
  86740. };
  86741. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  86742. return this.needAlphaBlending();
  86743. };
  86744. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  86745. if (this.isFrozen) {
  86746. if (this._wasPreviouslyReady && subMesh.effect) {
  86747. return true;
  86748. }
  86749. }
  86750. if (!subMesh._materialDefines) {
  86751. subMesh._materialDefines = new GridMaterialDefines();
  86752. }
  86753. var defines = subMesh._materialDefines;
  86754. var scene = this.getScene();
  86755. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  86756. if (this._renderId === scene.getRenderId()) {
  86757. return true;
  86758. }
  86759. }
  86760. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  86761. defines.TRANSPARENT = !defines.TRANSPARENT;
  86762. defines.markAsUnprocessed();
  86763. }
  86764. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  86765. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  86766. defines.markAsUnprocessed();
  86767. }
  86768. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  86769. // Get correct effect
  86770. if (defines.isDirty) {
  86771. defines.markAsProcessed();
  86772. scene.resetCachedMaterial();
  86773. // Attributes
  86774. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  86775. // Defines
  86776. var join = defines.toString();
  86777. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  86778. }
  86779. if (!subMesh.effect || !subMesh.effect.isReady()) {
  86780. return false;
  86781. }
  86782. this._renderId = scene.getRenderId();
  86783. this._wasPreviouslyReady = true;
  86784. return true;
  86785. };
  86786. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  86787. var scene = this.getScene();
  86788. var defines = subMesh._materialDefines;
  86789. if (!defines) {
  86790. return;
  86791. }
  86792. var effect = subMesh.effect;
  86793. if (!effect) {
  86794. return;
  86795. }
  86796. this._activeEffect = effect;
  86797. // Matrices
  86798. this.bindOnlyWorldMatrix(world);
  86799. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  86800. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  86801. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  86802. // Uniforms
  86803. if (this._mustRebind(scene, effect)) {
  86804. this._activeEffect.setColor3("mainColor", this.mainColor);
  86805. this._activeEffect.setColor3("lineColor", this.lineColor);
  86806. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  86807. this._gridControl.x = this.gridRatio;
  86808. this._gridControl.y = Math.round(this.majorUnitFrequency);
  86809. this._gridControl.z = this.minorUnitVisibility;
  86810. this._gridControl.w = this.opacity;
  86811. this._activeEffect.setVector4("gridControl", this._gridControl);
  86812. }
  86813. // Fog
  86814. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  86815. this._afterBind(mesh, this._activeEffect);
  86816. };
  86817. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  86818. _super.prototype.dispose.call(this, forceDisposeEffect);
  86819. };
  86820. GridMaterial.prototype.clone = function (name) {
  86821. var _this = this;
  86822. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  86823. };
  86824. GridMaterial.prototype.serialize = function () {
  86825. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  86826. serializationObject.customType = "BABYLON.GridMaterial";
  86827. return serializationObject;
  86828. };
  86829. GridMaterial.prototype.getClassName = function () {
  86830. return "GridMaterial";
  86831. };
  86832. GridMaterial.Parse = function (source, scene, rootUrl) {
  86833. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  86834. };
  86835. __decorate([
  86836. BABYLON.serializeAsColor3()
  86837. ], GridMaterial.prototype, "mainColor", void 0);
  86838. __decorate([
  86839. BABYLON.serializeAsColor3()
  86840. ], GridMaterial.prototype, "lineColor", void 0);
  86841. __decorate([
  86842. BABYLON.serialize()
  86843. ], GridMaterial.prototype, "gridRatio", void 0);
  86844. __decorate([
  86845. BABYLON.serializeAsColor3()
  86846. ], GridMaterial.prototype, "gridOffset", void 0);
  86847. __decorate([
  86848. BABYLON.serialize()
  86849. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  86850. __decorate([
  86851. BABYLON.serialize()
  86852. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  86853. __decorate([
  86854. BABYLON.serialize()
  86855. ], GridMaterial.prototype, "opacity", void 0);
  86856. __decorate([
  86857. BABYLON.serialize()
  86858. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  86859. return GridMaterial;
  86860. }(BABYLON.PushMaterial));
  86861. BABYLON.GridMaterial = GridMaterial;
  86862. })(BABYLON || (BABYLON = {}));
  86863. //# sourceMappingURL=babylon.gridmaterial.js.map
  86864. 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}";
  86865. 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}";
  86866. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  86867. var BABYLON;
  86868. (function (BABYLON) {
  86869. var GLTFLoaderCoordinateSystemMode;
  86870. (function (GLTFLoaderCoordinateSystemMode) {
  86871. /**
  86872. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  86873. */
  86874. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  86875. /**
  86876. * Sets the useRightHandedSystem flag on the scene.
  86877. */
  86878. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  86879. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  86880. var GLTFLoaderAnimationStartMode;
  86881. (function (GLTFLoaderAnimationStartMode) {
  86882. /**
  86883. * No animation will start.
  86884. */
  86885. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  86886. /**
  86887. * The first animation will start.
  86888. */
  86889. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  86890. /**
  86891. * All animations will start.
  86892. */
  86893. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  86894. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  86895. var GLTFFileLoader = /** @class */ (function () {
  86896. function GLTFFileLoader() {
  86897. // #region Common options
  86898. /**
  86899. * Raised when the asset has been parsed.
  86900. * The data.json property stores the glTF JSON.
  86901. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  86902. */
  86903. this.onParsedObservable = new BABYLON.Observable();
  86904. // #endregion
  86905. // #region V2 options
  86906. /**
  86907. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  86908. */
  86909. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  86910. /**
  86911. * The animation start mode (NONE, FIRST, ALL).
  86912. */
  86913. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  86914. /**
  86915. * Set to true to compile materials before raising the success callback.
  86916. */
  86917. this.compileMaterials = false;
  86918. /**
  86919. * Set to true to also compile materials with clip planes.
  86920. */
  86921. this.useClipPlane = false;
  86922. /**
  86923. * Set to true to compile shadow generators before raising the success callback.
  86924. */
  86925. this.compileShadowGenerators = false;
  86926. /**
  86927. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  86928. */
  86929. this.onMeshLoadedObservable = new BABYLON.Observable();
  86930. /**
  86931. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  86932. */
  86933. this.onTextureLoadedObservable = new BABYLON.Observable();
  86934. /**
  86935. * Raised when the loader creates a material after parsing the glTF properties of the material.
  86936. */
  86937. this.onMaterialLoadedObservable = new BABYLON.Observable();
  86938. /**
  86939. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  86940. * For assets with LODs, raised when all of the LODs are complete.
  86941. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  86942. */
  86943. this.onCompleteObservable = new BABYLON.Observable();
  86944. /**
  86945. * Raised when the loader is disposed.
  86946. */
  86947. this.onDisposeObservable = new BABYLON.Observable();
  86948. // #endregion
  86949. this._loader = null;
  86950. this.name = "gltf";
  86951. this.extensions = {
  86952. ".gltf": { isBinary: false },
  86953. ".glb": { isBinary: true }
  86954. };
  86955. }
  86956. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  86957. set: function (callback) {
  86958. if (this._onParsedObserver) {
  86959. this.onParsedObservable.remove(this._onParsedObserver);
  86960. }
  86961. this._onParsedObserver = this.onParsedObservable.add(callback);
  86962. },
  86963. enumerable: true,
  86964. configurable: true
  86965. });
  86966. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  86967. set: function (callback) {
  86968. if (this._onMeshLoadedObserver) {
  86969. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  86970. }
  86971. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  86972. },
  86973. enumerable: true,
  86974. configurable: true
  86975. });
  86976. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  86977. set: function (callback) {
  86978. if (this._onTextureLoadedObserver) {
  86979. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  86980. }
  86981. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  86982. },
  86983. enumerable: true,
  86984. configurable: true
  86985. });
  86986. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  86987. set: function (callback) {
  86988. if (this._onMaterialLoadedObserver) {
  86989. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  86990. }
  86991. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  86992. },
  86993. enumerable: true,
  86994. configurable: true
  86995. });
  86996. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  86997. set: function (callback) {
  86998. if (this._onCompleteObserver) {
  86999. this.onCompleteObservable.remove(this._onCompleteObserver);
  87000. }
  87001. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  87002. },
  87003. enumerable: true,
  87004. configurable: true
  87005. });
  87006. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  87007. set: function (callback) {
  87008. if (this._onDisposeObserver) {
  87009. this.onDisposeObservable.remove(this._onDisposeObserver);
  87010. }
  87011. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  87012. },
  87013. enumerable: true,
  87014. configurable: true
  87015. });
  87016. /**
  87017. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  87018. */
  87019. GLTFFileLoader.prototype.dispose = function () {
  87020. if (this._loader) {
  87021. this._loader.dispose();
  87022. this._loader = null;
  87023. }
  87024. this.onParsedObservable.clear();
  87025. this.onMeshLoadedObservable.clear();
  87026. this.onTextureLoadedObservable.clear();
  87027. this.onMaterialLoadedObservable.clear();
  87028. this.onCompleteObservable.clear();
  87029. this.onDisposeObservable.notifyObservers(this);
  87030. this.onDisposeObservable.clear();
  87031. };
  87032. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  87033. try {
  87034. var loaderData = this._parse(data);
  87035. this._loader = this._getLoader(loaderData);
  87036. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  87037. }
  87038. catch (e) {
  87039. if (onError) {
  87040. onError(e.message, e);
  87041. }
  87042. else {
  87043. BABYLON.Tools.Error(e.message);
  87044. }
  87045. }
  87046. };
  87047. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  87048. try {
  87049. var loaderData = this._parse(data);
  87050. this._loader = this._getLoader(loaderData);
  87051. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  87052. }
  87053. catch (e) {
  87054. if (onError) {
  87055. onError(e.message, e);
  87056. }
  87057. else {
  87058. BABYLON.Tools.Error(e.message);
  87059. }
  87060. }
  87061. };
  87062. GLTFFileLoader.prototype.loadAssetsAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  87063. try {
  87064. var loaderData = this._parse(data);
  87065. this._loader = this._getLoader(loaderData);
  87066. this._loader.importMeshAsync(null, scene, loaderData, rootUrl, function (meshes, particleSystems, skeletons) {
  87067. var container = new BABYLON.AssetContainer(scene);
  87068. Array.prototype.push.apply(container.meshes, meshes);
  87069. Array.prototype.push.apply(container.particleSystems, particleSystems);
  87070. Array.prototype.push.apply(container.skeletons, skeletons);
  87071. container.removeAllFromScene();
  87072. onSuccess(container);
  87073. }, onProgress, onError);
  87074. }
  87075. catch (e) {
  87076. if (onError) {
  87077. onError(e.message, e);
  87078. }
  87079. else {
  87080. BABYLON.Tools.Error(e.message);
  87081. }
  87082. }
  87083. };
  87084. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  87085. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  87086. };
  87087. GLTFFileLoader.prototype.createPlugin = function () {
  87088. return new GLTFFileLoader();
  87089. };
  87090. GLTFFileLoader.prototype._parse = function (data) {
  87091. var parsedData;
  87092. if (data instanceof ArrayBuffer) {
  87093. parsedData = GLTFFileLoader._parseBinary(data);
  87094. }
  87095. else {
  87096. parsedData = {
  87097. json: JSON.parse(data),
  87098. bin: null
  87099. };
  87100. }
  87101. this.onParsedObservable.notifyObservers(parsedData);
  87102. return parsedData;
  87103. };
  87104. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  87105. var _this = this;
  87106. var loaderVersion = { major: 2, minor: 0 };
  87107. var asset = loaderData.json.asset || {};
  87108. var version = GLTFFileLoader._parseVersion(asset.version);
  87109. if (!version) {
  87110. throw new Error("Invalid version: " + asset.version);
  87111. }
  87112. if (asset.minVersion !== undefined) {
  87113. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  87114. if (!minVersion) {
  87115. throw new Error("Invalid minimum version: " + asset.minVersion);
  87116. }
  87117. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  87118. throw new Error("Incompatible minimum version: " + asset.minVersion);
  87119. }
  87120. }
  87121. var createLoaders = {
  87122. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  87123. 2: GLTFFileLoader.CreateGLTFLoaderV2
  87124. };
  87125. var createLoader = createLoaders[version.major];
  87126. if (!createLoader) {
  87127. throw new Error("Unsupported version: " + asset.version);
  87128. }
  87129. var loader = createLoader();
  87130. loader.coordinateSystemMode = this.coordinateSystemMode;
  87131. loader.animationStartMode = this.animationStartMode;
  87132. loader.compileMaterials = this.compileMaterials;
  87133. loader.useClipPlane = this.useClipPlane;
  87134. loader.compileShadowGenerators = this.compileShadowGenerators;
  87135. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  87136. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  87137. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  87138. loader.onCompleteObservable.add(function () { return _this.onCompleteObservable.notifyObservers(_this); });
  87139. return loader;
  87140. };
  87141. GLTFFileLoader._parseBinary = function (data) {
  87142. var Binary = {
  87143. Magic: 0x46546C67
  87144. };
  87145. var binaryReader = new BinaryReader(data);
  87146. var magic = binaryReader.readUint32();
  87147. if (magic !== Binary.Magic) {
  87148. throw new Error("Unexpected magic: " + magic);
  87149. }
  87150. var version = binaryReader.readUint32();
  87151. switch (version) {
  87152. case 1: return GLTFFileLoader._parseV1(binaryReader);
  87153. case 2: return GLTFFileLoader._parseV2(binaryReader);
  87154. }
  87155. throw new Error("Unsupported version: " + version);
  87156. };
  87157. GLTFFileLoader._parseV1 = function (binaryReader) {
  87158. var ContentFormat = {
  87159. JSON: 0
  87160. };
  87161. var length = binaryReader.readUint32();
  87162. if (length != binaryReader.getLength()) {
  87163. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  87164. }
  87165. var contentLength = binaryReader.readUint32();
  87166. var contentFormat = binaryReader.readUint32();
  87167. var content;
  87168. switch (contentFormat) {
  87169. case ContentFormat.JSON: {
  87170. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  87171. break;
  87172. }
  87173. default: {
  87174. throw new Error("Unexpected content format: " + contentFormat);
  87175. }
  87176. }
  87177. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  87178. var body = binaryReader.readUint8Array(bytesRemaining);
  87179. return {
  87180. json: content,
  87181. bin: body
  87182. };
  87183. };
  87184. GLTFFileLoader._parseV2 = function (binaryReader) {
  87185. var ChunkFormat = {
  87186. JSON: 0x4E4F534A,
  87187. BIN: 0x004E4942
  87188. };
  87189. var length = binaryReader.readUint32();
  87190. if (length !== binaryReader.getLength()) {
  87191. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  87192. }
  87193. // JSON chunk
  87194. var chunkLength = binaryReader.readUint32();
  87195. var chunkFormat = binaryReader.readUint32();
  87196. if (chunkFormat !== ChunkFormat.JSON) {
  87197. throw new Error("First chunk format is not JSON");
  87198. }
  87199. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  87200. // Look for BIN chunk
  87201. var bin = null;
  87202. while (binaryReader.getPosition() < binaryReader.getLength()) {
  87203. var chunkLength_1 = binaryReader.readUint32();
  87204. var chunkFormat_1 = binaryReader.readUint32();
  87205. switch (chunkFormat_1) {
  87206. case ChunkFormat.JSON: {
  87207. throw new Error("Unexpected JSON chunk");
  87208. }
  87209. case ChunkFormat.BIN: {
  87210. bin = binaryReader.readUint8Array(chunkLength_1);
  87211. break;
  87212. }
  87213. default: {
  87214. // ignore unrecognized chunkFormat
  87215. binaryReader.skipBytes(chunkLength_1);
  87216. break;
  87217. }
  87218. }
  87219. }
  87220. return {
  87221. json: json,
  87222. bin: bin
  87223. };
  87224. };
  87225. GLTFFileLoader._parseVersion = function (version) {
  87226. if (version === "1.0" || version === "1.0.1") {
  87227. return {
  87228. major: 1,
  87229. minor: 0
  87230. };
  87231. }
  87232. var match = (version + "").match(/^(\d+)\.(\d+)/);
  87233. if (!match) {
  87234. return null;
  87235. }
  87236. return {
  87237. major: parseInt(match[1]),
  87238. minor: parseInt(match[2])
  87239. };
  87240. };
  87241. GLTFFileLoader._compareVersion = function (a, b) {
  87242. if (a.major > b.major)
  87243. return 1;
  87244. if (a.major < b.major)
  87245. return -1;
  87246. if (a.minor > b.minor)
  87247. return 1;
  87248. if (a.minor < b.minor)
  87249. return -1;
  87250. return 0;
  87251. };
  87252. GLTFFileLoader._decodeBufferToText = function (buffer) {
  87253. var result = "";
  87254. var length = buffer.byteLength;
  87255. for (var i = 0; i < length; i++) {
  87256. result += String.fromCharCode(buffer[i]);
  87257. }
  87258. return result;
  87259. };
  87260. // #endregion
  87261. // #region V1 options
  87262. GLTFFileLoader.IncrementalLoading = true;
  87263. GLTFFileLoader.HomogeneousCoordinates = false;
  87264. return GLTFFileLoader;
  87265. }());
  87266. BABYLON.GLTFFileLoader = GLTFFileLoader;
  87267. var BinaryReader = /** @class */ (function () {
  87268. function BinaryReader(arrayBuffer) {
  87269. this._arrayBuffer = arrayBuffer;
  87270. this._dataView = new DataView(arrayBuffer);
  87271. this._byteOffset = 0;
  87272. }
  87273. BinaryReader.prototype.getPosition = function () {
  87274. return this._byteOffset;
  87275. };
  87276. BinaryReader.prototype.getLength = function () {
  87277. return this._arrayBuffer.byteLength;
  87278. };
  87279. BinaryReader.prototype.readUint32 = function () {
  87280. var value = this._dataView.getUint32(this._byteOffset, true);
  87281. this._byteOffset += 4;
  87282. return value;
  87283. };
  87284. BinaryReader.prototype.readUint8Array = function (length) {
  87285. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  87286. this._byteOffset += length;
  87287. return value;
  87288. };
  87289. BinaryReader.prototype.skipBytes = function (length) {
  87290. this._byteOffset += length;
  87291. };
  87292. return BinaryReader;
  87293. }());
  87294. if (BABYLON.SceneLoader) {
  87295. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  87296. }
  87297. })(BABYLON || (BABYLON = {}));
  87298. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  87299. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  87300. var BABYLON;
  87301. (function (BABYLON) {
  87302. var GLTF1;
  87303. (function (GLTF1) {
  87304. /**
  87305. * Enums
  87306. */
  87307. var EComponentType;
  87308. (function (EComponentType) {
  87309. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  87310. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  87311. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  87312. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  87313. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  87314. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  87315. var EShaderType;
  87316. (function (EShaderType) {
  87317. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  87318. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  87319. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  87320. var EParameterType;
  87321. (function (EParameterType) {
  87322. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  87323. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  87324. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  87325. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  87326. EParameterType[EParameterType["INT"] = 5124] = "INT";
  87327. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  87328. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  87329. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  87330. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  87331. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  87332. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  87333. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  87334. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  87335. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  87336. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  87337. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  87338. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  87339. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  87340. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  87341. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  87342. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  87343. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  87344. var ETextureWrapMode;
  87345. (function (ETextureWrapMode) {
  87346. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  87347. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  87348. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  87349. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  87350. var ETextureFilterType;
  87351. (function (ETextureFilterType) {
  87352. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  87353. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  87354. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  87355. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  87356. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  87357. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  87358. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  87359. var ETextureFormat;
  87360. (function (ETextureFormat) {
  87361. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  87362. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  87363. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  87364. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  87365. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  87366. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  87367. var ECullingType;
  87368. (function (ECullingType) {
  87369. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  87370. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  87371. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  87372. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  87373. var EBlendingFunction;
  87374. (function (EBlendingFunction) {
  87375. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  87376. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  87377. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  87378. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  87379. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  87380. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  87381. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  87382. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  87383. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  87384. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  87385. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  87386. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  87387. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  87388. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  87389. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  87390. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  87391. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  87392. })(BABYLON || (BABYLON = {}));
  87393. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  87394. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  87395. var BABYLON;
  87396. (function (BABYLON) {
  87397. var GLTF1;
  87398. (function (GLTF1) {
  87399. /**
  87400. * Tokenizer. Used for shaders compatibility
  87401. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  87402. */
  87403. var ETokenType;
  87404. (function (ETokenType) {
  87405. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  87406. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  87407. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  87408. })(ETokenType || (ETokenType = {}));
  87409. var Tokenizer = /** @class */ (function () {
  87410. function Tokenizer(toParse) {
  87411. this._pos = 0;
  87412. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  87413. this._toParse = toParse;
  87414. this._maxPos = toParse.length;
  87415. }
  87416. Tokenizer.prototype.getNextToken = function () {
  87417. if (this.isEnd())
  87418. return ETokenType.END_OF_INPUT;
  87419. this.currentString = this.read();
  87420. this.currentToken = ETokenType.UNKNOWN;
  87421. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  87422. this.currentToken = ETokenType.IDENTIFIER;
  87423. this.currentIdentifier = this.currentString;
  87424. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  87425. this.currentIdentifier += this.currentString;
  87426. this.forward();
  87427. }
  87428. }
  87429. return this.currentToken;
  87430. };
  87431. Tokenizer.prototype.peek = function () {
  87432. return this._toParse[this._pos];
  87433. };
  87434. Tokenizer.prototype.read = function () {
  87435. return this._toParse[this._pos++];
  87436. };
  87437. Tokenizer.prototype.forward = function () {
  87438. this._pos++;
  87439. };
  87440. Tokenizer.prototype.isEnd = function () {
  87441. return this._pos >= this._maxPos;
  87442. };
  87443. return Tokenizer;
  87444. }());
  87445. /**
  87446. * Values
  87447. */
  87448. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  87449. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  87450. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  87451. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  87452. /**
  87453. * Parse
  87454. */
  87455. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  87456. for (var buf in parsedBuffers) {
  87457. var parsedBuffer = parsedBuffers[buf];
  87458. gltfRuntime.buffers[buf] = parsedBuffer;
  87459. gltfRuntime.buffersCount++;
  87460. }
  87461. };
  87462. var parseShaders = function (parsedShaders, gltfRuntime) {
  87463. for (var sha in parsedShaders) {
  87464. var parsedShader = parsedShaders[sha];
  87465. gltfRuntime.shaders[sha] = parsedShader;
  87466. gltfRuntime.shaderscount++;
  87467. }
  87468. };
  87469. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  87470. for (var object in parsedObjects) {
  87471. var parsedObject = parsedObjects[object];
  87472. gltfRuntime[runtimeProperty][object] = parsedObject;
  87473. }
  87474. };
  87475. /**
  87476. * Utils
  87477. */
  87478. var normalizeUVs = function (buffer) {
  87479. if (!buffer) {
  87480. return;
  87481. }
  87482. for (var i = 0; i < buffer.length / 2; i++) {
  87483. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  87484. }
  87485. };
  87486. var getAttribute = function (attributeParameter) {
  87487. if (attributeParameter.semantic === "NORMAL") {
  87488. return "normal";
  87489. }
  87490. else if (attributeParameter.semantic === "POSITION") {
  87491. return "position";
  87492. }
  87493. else if (attributeParameter.semantic === "JOINT") {
  87494. return "matricesIndices";
  87495. }
  87496. else if (attributeParameter.semantic === "WEIGHT") {
  87497. return "matricesWeights";
  87498. }
  87499. else if (attributeParameter.semantic === "COLOR") {
  87500. return "color";
  87501. }
  87502. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  87503. var channel = Number(attributeParameter.semantic.split("_")[1]);
  87504. return "uv" + (channel === 0 ? "" : channel + 1);
  87505. }
  87506. return null;
  87507. };
  87508. /**
  87509. * Loads and creates animations
  87510. */
  87511. var loadAnimations = function (gltfRuntime) {
  87512. for (var anim in gltfRuntime.animations) {
  87513. var animation = gltfRuntime.animations[anim];
  87514. if (!animation.channels || !animation.samplers) {
  87515. continue;
  87516. }
  87517. var lastAnimation = null;
  87518. for (var i = 0; i < animation.channels.length; i++) {
  87519. // Get parameters and load buffers
  87520. var channel = animation.channels[i];
  87521. var sampler = animation.samplers[channel.sampler];
  87522. if (!sampler) {
  87523. continue;
  87524. }
  87525. var inputData = null;
  87526. var outputData = null;
  87527. if (animation.parameters) {
  87528. inputData = animation.parameters[sampler.input];
  87529. outputData = animation.parameters[sampler.output];
  87530. }
  87531. else {
  87532. inputData = sampler.input;
  87533. outputData = sampler.output;
  87534. }
  87535. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  87536. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  87537. var targetID = channel.target.id;
  87538. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  87539. if (targetNode === null) {
  87540. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  87541. }
  87542. if (targetNode === null) {
  87543. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  87544. continue;
  87545. }
  87546. var isBone = targetNode instanceof BABYLON.Bone;
  87547. // Get target path (position, rotation or scaling)
  87548. var targetPath = channel.target.path;
  87549. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  87550. if (targetPathIndex !== -1) {
  87551. targetPath = babylonAnimationPaths[targetPathIndex];
  87552. }
  87553. // Determine animation type
  87554. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  87555. if (!isBone) {
  87556. if (targetPath === "rotationQuaternion") {
  87557. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  87558. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  87559. }
  87560. else {
  87561. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  87562. }
  87563. }
  87564. // Create animation and key frames
  87565. var babylonAnimation = null;
  87566. var keys = [];
  87567. var arrayOffset = 0;
  87568. var modifyKey = false;
  87569. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  87570. babylonAnimation = lastAnimation;
  87571. modifyKey = true;
  87572. }
  87573. if (!modifyKey) {
  87574. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  87575. }
  87576. // For each frame
  87577. for (var j = 0; j < bufferInput.length; j++) {
  87578. var value = null;
  87579. if (targetPath === "rotationQuaternion") {
  87580. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  87581. arrayOffset += 4;
  87582. }
  87583. else {
  87584. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  87585. arrayOffset += 3;
  87586. }
  87587. if (isBone) {
  87588. var bone = targetNode;
  87589. var translation = BABYLON.Vector3.Zero();
  87590. var rotationQuaternion = new BABYLON.Quaternion();
  87591. var scaling = BABYLON.Vector3.Zero();
  87592. // Warning on decompose
  87593. var mat = bone.getBaseMatrix();
  87594. if (modifyKey && lastAnimation) {
  87595. mat = lastAnimation.getKeys()[j].value;
  87596. }
  87597. mat.decompose(scaling, rotationQuaternion, translation);
  87598. if (targetPath === "position") {
  87599. translation = value;
  87600. }
  87601. else if (targetPath === "rotationQuaternion") {
  87602. rotationQuaternion = value;
  87603. }
  87604. else {
  87605. scaling = value;
  87606. }
  87607. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  87608. }
  87609. if (!modifyKey) {
  87610. keys.push({
  87611. frame: bufferInput[j],
  87612. value: value
  87613. });
  87614. }
  87615. else if (lastAnimation) {
  87616. lastAnimation.getKeys()[j].value = value;
  87617. }
  87618. }
  87619. // Finish
  87620. if (!modifyKey && babylonAnimation) {
  87621. babylonAnimation.setKeys(keys);
  87622. targetNode.animations.push(babylonAnimation);
  87623. }
  87624. lastAnimation = babylonAnimation;
  87625. gltfRuntime.scene.stopAnimation(targetNode);
  87626. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  87627. }
  87628. }
  87629. };
  87630. /**
  87631. * Returns the bones transformation matrix
  87632. */
  87633. var configureBoneTransformation = function (node) {
  87634. var mat = null;
  87635. if (node.translation || node.rotation || node.scale) {
  87636. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  87637. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  87638. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  87639. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  87640. }
  87641. else {
  87642. mat = BABYLON.Matrix.FromArray(node.matrix);
  87643. }
  87644. return mat;
  87645. };
  87646. /**
  87647. * Returns the parent bone
  87648. */
  87649. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  87650. // Try to find
  87651. for (var i = 0; i < newSkeleton.bones.length; i++) {
  87652. if (newSkeleton.bones[i].name === jointName) {
  87653. return newSkeleton.bones[i];
  87654. }
  87655. }
  87656. // Not found, search in gltf nodes
  87657. var nodes = gltfRuntime.nodes;
  87658. for (var nde in nodes) {
  87659. var node = nodes[nde];
  87660. if (!node.jointName) {
  87661. continue;
  87662. }
  87663. var children = node.children;
  87664. for (var i = 0; i < children.length; i++) {
  87665. var child = gltfRuntime.nodes[children[i]];
  87666. if (!child.jointName) {
  87667. continue;
  87668. }
  87669. if (child.jointName === jointName) {
  87670. var mat = configureBoneTransformation(node);
  87671. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  87672. bone.id = nde;
  87673. return bone;
  87674. }
  87675. }
  87676. }
  87677. return null;
  87678. };
  87679. /**
  87680. * Returns the appropriate root node
  87681. */
  87682. var getNodeToRoot = function (nodesToRoot, id) {
  87683. for (var i = 0; i < nodesToRoot.length; i++) {
  87684. var nodeToRoot = nodesToRoot[i];
  87685. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  87686. var child = nodeToRoot.node.children[j];
  87687. if (child === id) {
  87688. return nodeToRoot.bone;
  87689. }
  87690. }
  87691. }
  87692. return null;
  87693. };
  87694. /**
  87695. * Returns the node with the joint name
  87696. */
  87697. var getJointNode = function (gltfRuntime, jointName) {
  87698. var nodes = gltfRuntime.nodes;
  87699. var node = nodes[jointName];
  87700. if (node) {
  87701. return {
  87702. node: node,
  87703. id: jointName
  87704. };
  87705. }
  87706. for (var nde in nodes) {
  87707. node = nodes[nde];
  87708. if (node.jointName === jointName) {
  87709. return {
  87710. node: node,
  87711. id: nde
  87712. };
  87713. }
  87714. }
  87715. return null;
  87716. };
  87717. /**
  87718. * Checks if a nodes is in joints
  87719. */
  87720. var nodeIsInJoints = function (skins, id) {
  87721. for (var i = 0; i < skins.jointNames.length; i++) {
  87722. if (skins.jointNames[i] === id) {
  87723. return true;
  87724. }
  87725. }
  87726. return false;
  87727. };
  87728. /**
  87729. * Fills the nodes to root for bones and builds hierarchy
  87730. */
  87731. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  87732. // Creates nodes for root
  87733. for (var nde in gltfRuntime.nodes) {
  87734. var node = gltfRuntime.nodes[nde];
  87735. var id = nde;
  87736. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  87737. continue;
  87738. }
  87739. // Create node to root bone
  87740. var mat = configureBoneTransformation(node);
  87741. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  87742. bone.id = id;
  87743. nodesToRoot.push({ bone: bone, node: node, id: id });
  87744. }
  87745. // Parenting
  87746. for (var i = 0; i < nodesToRoot.length; i++) {
  87747. var nodeToRoot = nodesToRoot[i];
  87748. var children = nodeToRoot.node.children;
  87749. for (var j = 0; j < children.length; j++) {
  87750. var child = null;
  87751. for (var k = 0; k < nodesToRoot.length; k++) {
  87752. if (nodesToRoot[k].id === children[j]) {
  87753. child = nodesToRoot[k];
  87754. break;
  87755. }
  87756. }
  87757. if (child) {
  87758. child.bone._parent = nodeToRoot.bone;
  87759. nodeToRoot.bone.children.push(child.bone);
  87760. }
  87761. }
  87762. }
  87763. };
  87764. /**
  87765. * Imports a skeleton
  87766. */
  87767. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  87768. if (!newSkeleton) {
  87769. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  87770. }
  87771. if (!skins.babylonSkeleton) {
  87772. return newSkeleton;
  87773. }
  87774. // Find the root bones
  87775. var nodesToRoot = [];
  87776. var nodesToRootToAdd = [];
  87777. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  87778. newSkeleton.bones = [];
  87779. // Joints
  87780. for (var i = 0; i < skins.jointNames.length; i++) {
  87781. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  87782. if (!jointNode) {
  87783. continue;
  87784. }
  87785. var node = jointNode.node;
  87786. if (!node) {
  87787. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  87788. continue;
  87789. }
  87790. var id = jointNode.id;
  87791. // Optimize, if the bone already exists...
  87792. var existingBone = gltfRuntime.scene.getBoneByID(id);
  87793. if (existingBone) {
  87794. newSkeleton.bones.push(existingBone);
  87795. continue;
  87796. }
  87797. // Search for parent bone
  87798. var foundBone = false;
  87799. var parentBone = null;
  87800. for (var j = 0; j < i; j++) {
  87801. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  87802. if (!jointNode_1) {
  87803. continue;
  87804. }
  87805. var joint = jointNode_1.node;
  87806. if (!joint) {
  87807. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  87808. continue;
  87809. }
  87810. var children = joint.children;
  87811. if (!children) {
  87812. continue;
  87813. }
  87814. foundBone = false;
  87815. for (var k = 0; k < children.length; k++) {
  87816. if (children[k] === id) {
  87817. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  87818. foundBone = true;
  87819. break;
  87820. }
  87821. }
  87822. if (foundBone) {
  87823. break;
  87824. }
  87825. }
  87826. // Create bone
  87827. var mat = configureBoneTransformation(node);
  87828. if (!parentBone && nodesToRoot.length > 0) {
  87829. parentBone = getNodeToRoot(nodesToRoot, id);
  87830. if (parentBone) {
  87831. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  87832. nodesToRootToAdd.push(parentBone);
  87833. }
  87834. }
  87835. }
  87836. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  87837. bone.id = id;
  87838. }
  87839. // Polish
  87840. var bones = newSkeleton.bones;
  87841. newSkeleton.bones = [];
  87842. for (var i = 0; i < skins.jointNames.length; i++) {
  87843. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  87844. if (!jointNode) {
  87845. continue;
  87846. }
  87847. for (var j = 0; j < bones.length; j++) {
  87848. if (bones[j].id === jointNode.id) {
  87849. newSkeleton.bones.push(bones[j]);
  87850. break;
  87851. }
  87852. }
  87853. }
  87854. newSkeleton.prepare();
  87855. // Finish
  87856. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  87857. newSkeleton.bones.push(nodesToRootToAdd[i]);
  87858. }
  87859. return newSkeleton;
  87860. };
  87861. /**
  87862. * Imports a mesh and its geometries
  87863. */
  87864. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  87865. if (!newMesh) {
  87866. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  87867. newMesh.id = id;
  87868. }
  87869. if (!node.babylonNode) {
  87870. return newMesh;
  87871. }
  87872. var subMaterials = [];
  87873. var vertexData = new BABYLON.VertexData();
  87874. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  87875. var verticesStarts = new Array();
  87876. var verticesCounts = new Array();
  87877. var indexStarts = new Array();
  87878. var indexCounts = new Array();
  87879. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  87880. var meshID = meshes[meshIndex];
  87881. var mesh = gltfRuntime.meshes[meshID];
  87882. if (!mesh) {
  87883. continue;
  87884. }
  87885. // Positions, normals and UVs
  87886. for (var i = 0; i < mesh.primitives.length; i++) {
  87887. // Temporary vertex data
  87888. var tempVertexData = new BABYLON.VertexData();
  87889. var primitive = mesh.primitives[i];
  87890. if (primitive.mode !== 4) {
  87891. // continue;
  87892. }
  87893. var attributes = primitive.attributes;
  87894. var accessor = null;
  87895. var buffer = null;
  87896. // Set positions, normal and uvs
  87897. for (var semantic in attributes) {
  87898. // Link accessor and buffer view
  87899. accessor = gltfRuntime.accessors[attributes[semantic]];
  87900. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  87901. if (semantic === "NORMAL") {
  87902. tempVertexData.normals = new Float32Array(buffer.length);
  87903. tempVertexData.normals.set(buffer);
  87904. }
  87905. else if (semantic === "POSITION") {
  87906. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  87907. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  87908. for (var j = 0; j < buffer.length; j += 4) {
  87909. tempVertexData.positions[j] = buffer[j];
  87910. tempVertexData.positions[j + 1] = buffer[j + 1];
  87911. tempVertexData.positions[j + 2] = buffer[j + 2];
  87912. }
  87913. }
  87914. else {
  87915. tempVertexData.positions = new Float32Array(buffer.length);
  87916. tempVertexData.positions.set(buffer);
  87917. }
  87918. verticesCounts.push(tempVertexData.positions.length);
  87919. }
  87920. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  87921. var channel = Number(semantic.split("_")[1]);
  87922. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  87923. var uvs = new Float32Array(buffer.length);
  87924. uvs.set(buffer);
  87925. normalizeUVs(uvs);
  87926. tempVertexData.set(uvs, uvKind);
  87927. }
  87928. else if (semantic === "JOINT") {
  87929. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  87930. tempVertexData.matricesIndices.set(buffer);
  87931. }
  87932. else if (semantic === "WEIGHT") {
  87933. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  87934. tempVertexData.matricesWeights.set(buffer);
  87935. }
  87936. else if (semantic === "COLOR") {
  87937. tempVertexData.colors = new Float32Array(buffer.length);
  87938. tempVertexData.colors.set(buffer);
  87939. }
  87940. }
  87941. // Indices
  87942. accessor = gltfRuntime.accessors[primitive.indices];
  87943. if (accessor) {
  87944. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  87945. tempVertexData.indices = new Int32Array(buffer.length);
  87946. tempVertexData.indices.set(buffer);
  87947. indexCounts.push(tempVertexData.indices.length);
  87948. }
  87949. else {
  87950. // Set indices on the fly
  87951. var indices = [];
  87952. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  87953. indices.push(j);
  87954. }
  87955. tempVertexData.indices = new Int32Array(indices);
  87956. indexCounts.push(tempVertexData.indices.length);
  87957. }
  87958. vertexData.merge(tempVertexData);
  87959. // Sub material
  87960. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  87961. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  87962. // Update vertices start and index start
  87963. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  87964. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  87965. }
  87966. }
  87967. var material;
  87968. if (subMaterials.length > 1) {
  87969. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  87970. material.subMaterials = subMaterials;
  87971. }
  87972. else {
  87973. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  87974. }
  87975. if (subMaterials.length === 1) {
  87976. material = subMaterials[0];
  87977. }
  87978. if (!newMesh.material) {
  87979. newMesh.material = material;
  87980. }
  87981. // Apply geometry
  87982. geometry.setAllVerticesData(vertexData, false);
  87983. newMesh.computeWorldMatrix(true);
  87984. // Apply submeshes
  87985. newMesh.subMeshes = [];
  87986. var index = 0;
  87987. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  87988. var meshID = meshes[meshIndex];
  87989. var mesh = gltfRuntime.meshes[meshID];
  87990. if (!mesh) {
  87991. continue;
  87992. }
  87993. for (var i = 0; i < mesh.primitives.length; i++) {
  87994. if (mesh.primitives[i].mode !== 4) {
  87995. //continue;
  87996. }
  87997. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  87998. index++;
  87999. }
  88000. }
  88001. // Finish
  88002. return newMesh;
  88003. };
  88004. /**
  88005. * Configure node transformation from position, rotation and scaling
  88006. */
  88007. var configureNode = function (newNode, position, rotation, scaling) {
  88008. if (newNode.position) {
  88009. newNode.position = position;
  88010. }
  88011. if (newNode.rotationQuaternion || newNode.rotation) {
  88012. newNode.rotationQuaternion = rotation;
  88013. }
  88014. if (newNode.scaling) {
  88015. newNode.scaling = scaling;
  88016. }
  88017. };
  88018. /**
  88019. * Configures node from transformation matrix
  88020. */
  88021. var configureNodeFromMatrix = function (newNode, node, parent) {
  88022. if (node.matrix) {
  88023. var position = new BABYLON.Vector3(0, 0, 0);
  88024. var rotation = new BABYLON.Quaternion();
  88025. var scaling = new BABYLON.Vector3(0, 0, 0);
  88026. var mat = BABYLON.Matrix.FromArray(node.matrix);
  88027. mat.decompose(scaling, rotation, position);
  88028. configureNode(newNode, position, rotation, scaling);
  88029. }
  88030. else if (node.translation && node.rotation && node.scale) {
  88031. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  88032. }
  88033. newNode.computeWorldMatrix(true);
  88034. };
  88035. /**
  88036. * Imports a node
  88037. */
  88038. var importNode = function (gltfRuntime, node, id, parent) {
  88039. var lastNode = null;
  88040. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  88041. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  88042. return null;
  88043. }
  88044. }
  88045. // Meshes
  88046. if (node.skin) {
  88047. if (node.meshes) {
  88048. var skin = gltfRuntime.skins[node.skin];
  88049. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  88050. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  88051. if (newMesh.skeleton === null) {
  88052. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  88053. if (!skin.babylonSkeleton) {
  88054. skin.babylonSkeleton = newMesh.skeleton;
  88055. }
  88056. }
  88057. lastNode = newMesh;
  88058. }
  88059. }
  88060. else if (node.meshes) {
  88061. /**
  88062. * Improve meshes property
  88063. */
  88064. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  88065. lastNode = newMesh;
  88066. }
  88067. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  88068. var light = gltfRuntime.lights[node.light];
  88069. if (light) {
  88070. if (light.type === "ambient") {
  88071. var ambienLight = light[light.type];
  88072. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  88073. hemiLight.name = node.name || "";
  88074. if (ambienLight.color) {
  88075. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  88076. }
  88077. lastNode = hemiLight;
  88078. }
  88079. else if (light.type === "directional") {
  88080. var directionalLight = light[light.type];
  88081. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  88082. dirLight.name = node.name || "";
  88083. if (directionalLight.color) {
  88084. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  88085. }
  88086. lastNode = dirLight;
  88087. }
  88088. else if (light.type === "point") {
  88089. var pointLight = light[light.type];
  88090. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  88091. ptLight.name = node.name || "";
  88092. if (pointLight.color) {
  88093. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  88094. }
  88095. lastNode = ptLight;
  88096. }
  88097. else if (light.type === "spot") {
  88098. var spotLight = light[light.type];
  88099. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  88100. spLight.name = node.name || "";
  88101. if (spotLight.color) {
  88102. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  88103. }
  88104. if (spotLight.fallOfAngle) {
  88105. spLight.angle = spotLight.fallOfAngle;
  88106. }
  88107. if (spotLight.fallOffExponent) {
  88108. spLight.exponent = spotLight.fallOffExponent;
  88109. }
  88110. lastNode = spLight;
  88111. }
  88112. }
  88113. }
  88114. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  88115. var camera = gltfRuntime.cameras[node.camera];
  88116. if (camera) {
  88117. if (camera.type === "orthographic") {
  88118. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  88119. orthoCamera.name = node.name || "";
  88120. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  88121. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  88122. lastNode = orthoCamera;
  88123. }
  88124. else if (camera.type === "perspective") {
  88125. var perspectiveCamera = camera[camera.type];
  88126. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  88127. persCamera.name = node.name || "";
  88128. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  88129. if (!perspectiveCamera.aspectRatio) {
  88130. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  88131. }
  88132. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  88133. persCamera.maxZ = perspectiveCamera.zfar;
  88134. persCamera.minZ = perspectiveCamera.znear;
  88135. }
  88136. lastNode = persCamera;
  88137. }
  88138. }
  88139. }
  88140. // Empty node
  88141. if (!node.jointName) {
  88142. if (node.babylonNode) {
  88143. return node.babylonNode;
  88144. }
  88145. else if (lastNode === null) {
  88146. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  88147. node.babylonNode = dummy;
  88148. lastNode = dummy;
  88149. }
  88150. }
  88151. if (lastNode !== null) {
  88152. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  88153. configureNodeFromMatrix(lastNode, node, parent);
  88154. }
  88155. else {
  88156. var translation = node.translation || [0, 0, 0];
  88157. var rotation = node.rotation || [0, 0, 0, 1];
  88158. var scale = node.scale || [1, 1, 1];
  88159. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  88160. }
  88161. lastNode.updateCache(true);
  88162. node.babylonNode = lastNode;
  88163. }
  88164. return lastNode;
  88165. };
  88166. /**
  88167. * Traverses nodes and creates them
  88168. */
  88169. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  88170. if (meshIncluded === void 0) { meshIncluded = false; }
  88171. var node = gltfRuntime.nodes[id];
  88172. var newNode = null;
  88173. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  88174. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  88175. meshIncluded = true;
  88176. }
  88177. else {
  88178. meshIncluded = false;
  88179. }
  88180. }
  88181. else {
  88182. meshIncluded = true;
  88183. }
  88184. if (!node.jointName && meshIncluded) {
  88185. newNode = importNode(gltfRuntime, node, id, parent);
  88186. if (newNode !== null) {
  88187. newNode.id = id;
  88188. newNode.parent = parent;
  88189. }
  88190. }
  88191. if (node.children) {
  88192. for (var i = 0; i < node.children.length; i++) {
  88193. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  88194. }
  88195. }
  88196. };
  88197. /**
  88198. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  88199. */
  88200. var postLoad = function (gltfRuntime) {
  88201. // Nodes
  88202. var currentScene = gltfRuntime.currentScene;
  88203. if (currentScene) {
  88204. for (var i = 0; i < currentScene.nodes.length; i++) {
  88205. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  88206. }
  88207. }
  88208. else {
  88209. for (var thing in gltfRuntime.scenes) {
  88210. currentScene = gltfRuntime.scenes[thing];
  88211. for (var i = 0; i < currentScene.nodes.length; i++) {
  88212. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  88213. }
  88214. }
  88215. }
  88216. // Set animations
  88217. loadAnimations(gltfRuntime);
  88218. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  88219. var skeleton = gltfRuntime.scene.skeletons[i];
  88220. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  88221. }
  88222. };
  88223. /**
  88224. * onBind shaderrs callback to set uniforms and matrices
  88225. */
  88226. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  88227. var materialValues = material.values || technique.parameters;
  88228. for (var unif in unTreatedUniforms) {
  88229. var uniform = unTreatedUniforms[unif];
  88230. var type = uniform.type;
  88231. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  88232. if (uniform.semantic && !uniform.source && !uniform.node) {
  88233. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  88234. }
  88235. else if (uniform.semantic && (uniform.source || uniform.node)) {
  88236. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  88237. if (source === null) {
  88238. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  88239. }
  88240. if (source === null) {
  88241. continue;
  88242. }
  88243. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  88244. }
  88245. }
  88246. else {
  88247. var value = materialValues[technique.uniforms[unif]];
  88248. if (!value) {
  88249. continue;
  88250. }
  88251. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  88252. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  88253. if (texture === null || texture === undefined) {
  88254. continue;
  88255. }
  88256. shaderMaterial.getEffect().setTexture(unif, texture);
  88257. }
  88258. else {
  88259. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  88260. }
  88261. }
  88262. }
  88263. onSuccess(shaderMaterial);
  88264. };
  88265. /**
  88266. * Prepare uniforms to send the only one time
  88267. * Loads the appropriate textures
  88268. */
  88269. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  88270. var materialValues = material.values || technique.parameters;
  88271. var techniqueUniforms = technique.uniforms;
  88272. /**
  88273. * Prepare values here (not matrices)
  88274. */
  88275. for (var unif in unTreatedUniforms) {
  88276. var uniform = unTreatedUniforms[unif];
  88277. var type = uniform.type;
  88278. var value = materialValues[techniqueUniforms[unif]];
  88279. if (value === undefined) {
  88280. // In case the value is the same for all materials
  88281. value = uniform.value;
  88282. }
  88283. if (!value) {
  88284. continue;
  88285. }
  88286. var onLoadTexture = function (uniformName) {
  88287. return function (texture) {
  88288. if (uniform.value && uniformName) {
  88289. // Static uniform
  88290. shaderMaterial.setTexture(uniformName, texture);
  88291. delete unTreatedUniforms[uniformName];
  88292. }
  88293. };
  88294. };
  88295. // Texture (sampler2D)
  88296. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  88297. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  88298. }
  88299. else {
  88300. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  88301. // Static uniform
  88302. delete unTreatedUniforms[unif];
  88303. }
  88304. }
  88305. }
  88306. };
  88307. /**
  88308. * Shader compilation failed
  88309. */
  88310. var onShaderCompileError = function (program, shaderMaterial, onError) {
  88311. return function (effect, error) {
  88312. shaderMaterial.dispose(true);
  88313. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  88314. };
  88315. };
  88316. /**
  88317. * Shader compilation success
  88318. */
  88319. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  88320. return function (_) {
  88321. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  88322. shaderMaterial.onBind = function (mesh) {
  88323. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  88324. };
  88325. };
  88326. };
  88327. /**
  88328. * Returns the appropriate uniform if already handled by babylon
  88329. */
  88330. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  88331. for (var unif in technique.uniforms) {
  88332. var uniform = technique.uniforms[unif];
  88333. var uniformParameter = technique.parameters[uniform];
  88334. if (tokenizer.currentIdentifier === unif) {
  88335. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  88336. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  88337. if (transformIndex !== -1) {
  88338. delete unTreatedUniforms[unif];
  88339. return babylonTransforms[transformIndex];
  88340. }
  88341. }
  88342. }
  88343. }
  88344. return tokenizer.currentIdentifier;
  88345. };
  88346. /**
  88347. * All shaders loaded. Create materials one by one
  88348. */
  88349. var importMaterials = function (gltfRuntime) {
  88350. // Create materials
  88351. for (var mat in gltfRuntime.materials) {
  88352. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  88353. }
  88354. };
  88355. /**
  88356. * Implementation of the base glTF spec
  88357. */
  88358. var GLTFLoaderBase = /** @class */ (function () {
  88359. function GLTFLoaderBase() {
  88360. }
  88361. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  88362. var gltfRuntime = {
  88363. extensions: {},
  88364. accessors: {},
  88365. buffers: {},
  88366. bufferViews: {},
  88367. meshes: {},
  88368. lights: {},
  88369. cameras: {},
  88370. nodes: {},
  88371. images: {},
  88372. textures: {},
  88373. shaders: {},
  88374. programs: {},
  88375. samplers: {},
  88376. techniques: {},
  88377. materials: {},
  88378. animations: {},
  88379. skins: {},
  88380. extensionsUsed: [],
  88381. scenes: {},
  88382. buffersCount: 0,
  88383. shaderscount: 0,
  88384. scene: scene,
  88385. rootUrl: rootUrl,
  88386. loadedBufferCount: 0,
  88387. loadedBufferViews: {},
  88388. loadedShaderCount: 0,
  88389. importOnlyMeshes: false,
  88390. dummyNodes: []
  88391. };
  88392. // Parse
  88393. if (parsedData.extensions) {
  88394. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  88395. }
  88396. if (parsedData.extensionsUsed) {
  88397. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  88398. }
  88399. if (parsedData.buffers) {
  88400. parseBuffers(parsedData.buffers, gltfRuntime);
  88401. }
  88402. if (parsedData.bufferViews) {
  88403. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  88404. }
  88405. if (parsedData.accessors) {
  88406. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  88407. }
  88408. if (parsedData.meshes) {
  88409. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  88410. }
  88411. if (parsedData.lights) {
  88412. parseObject(parsedData.lights, "lights", gltfRuntime);
  88413. }
  88414. if (parsedData.cameras) {
  88415. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  88416. }
  88417. if (parsedData.nodes) {
  88418. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  88419. }
  88420. if (parsedData.images) {
  88421. parseObject(parsedData.images, "images", gltfRuntime);
  88422. }
  88423. if (parsedData.textures) {
  88424. parseObject(parsedData.textures, "textures", gltfRuntime);
  88425. }
  88426. if (parsedData.shaders) {
  88427. parseShaders(parsedData.shaders, gltfRuntime);
  88428. }
  88429. if (parsedData.programs) {
  88430. parseObject(parsedData.programs, "programs", gltfRuntime);
  88431. }
  88432. if (parsedData.samplers) {
  88433. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  88434. }
  88435. if (parsedData.techniques) {
  88436. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  88437. }
  88438. if (parsedData.materials) {
  88439. parseObject(parsedData.materials, "materials", gltfRuntime);
  88440. }
  88441. if (parsedData.animations) {
  88442. parseObject(parsedData.animations, "animations", gltfRuntime);
  88443. }
  88444. if (parsedData.skins) {
  88445. parseObject(parsedData.skins, "skins", gltfRuntime);
  88446. }
  88447. if (parsedData.scenes) {
  88448. gltfRuntime.scenes = parsedData.scenes;
  88449. }
  88450. if (parsedData.scene && parsedData.scenes) {
  88451. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  88452. }
  88453. return gltfRuntime;
  88454. };
  88455. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  88456. var buffer = gltfRuntime.buffers[id];
  88457. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  88458. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  88459. }
  88460. else {
  88461. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  88462. if (request) {
  88463. onError(request.status + " " + request.statusText);
  88464. }
  88465. });
  88466. }
  88467. };
  88468. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  88469. var texture = gltfRuntime.textures[id];
  88470. if (!texture || !texture.source) {
  88471. onError("");
  88472. return;
  88473. }
  88474. if (texture.babylonTexture) {
  88475. onSuccess(null);
  88476. return;
  88477. }
  88478. var source = gltfRuntime.images[texture.source];
  88479. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  88480. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  88481. }
  88482. else {
  88483. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  88484. if (request) {
  88485. onError(request.status + " " + request.statusText);
  88486. }
  88487. });
  88488. }
  88489. };
  88490. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  88491. var texture = gltfRuntime.textures[id];
  88492. if (texture.babylonTexture) {
  88493. onSuccess(texture.babylonTexture);
  88494. return;
  88495. }
  88496. var sampler = gltfRuntime.samplers[texture.sampler];
  88497. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  88498. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  88499. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  88500. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  88501. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  88502. var blob = new Blob([buffer]);
  88503. var blobURL = URL.createObjectURL(blob);
  88504. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  88505. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  88506. if (sampler.wrapS !== undefined) {
  88507. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  88508. }
  88509. if (sampler.wrapT !== undefined) {
  88510. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  88511. }
  88512. newTexture.name = id;
  88513. texture.babylonTexture = newTexture;
  88514. onSuccess(newTexture);
  88515. };
  88516. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  88517. var shader = gltfRuntime.shaders[id];
  88518. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  88519. var shaderString = atob(shader.uri.split(",")[1]);
  88520. onSuccess(shaderString);
  88521. }
  88522. else {
  88523. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  88524. if (request) {
  88525. onError(request.status + " " + request.statusText);
  88526. }
  88527. });
  88528. }
  88529. };
  88530. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  88531. var material = gltfRuntime.materials[id];
  88532. if (!material.technique) {
  88533. if (onError) {
  88534. onError("No technique found.");
  88535. }
  88536. return;
  88537. }
  88538. var technique = gltfRuntime.techniques[material.technique];
  88539. if (!technique) {
  88540. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  88541. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  88542. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  88543. onSuccess(defaultMaterial);
  88544. return;
  88545. }
  88546. var program = gltfRuntime.programs[technique.program];
  88547. var states = technique.states;
  88548. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  88549. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  88550. var newVertexShader = "";
  88551. var newPixelShader = "";
  88552. var vertexTokenizer = new Tokenizer(vertexShader);
  88553. var pixelTokenizer = new Tokenizer(pixelShader);
  88554. var unTreatedUniforms = {};
  88555. var uniforms = [];
  88556. var attributes = [];
  88557. var samplers = [];
  88558. // Fill uniform, sampler2D and attributes
  88559. for (var unif in technique.uniforms) {
  88560. var uniform = technique.uniforms[unif];
  88561. var uniformParameter = technique.parameters[uniform];
  88562. unTreatedUniforms[unif] = uniformParameter;
  88563. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  88564. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  88565. if (transformIndex !== -1) {
  88566. uniforms.push(babylonTransforms[transformIndex]);
  88567. delete unTreatedUniforms[unif];
  88568. }
  88569. else {
  88570. uniforms.push(unif);
  88571. }
  88572. }
  88573. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  88574. samplers.push(unif);
  88575. }
  88576. else {
  88577. uniforms.push(unif);
  88578. }
  88579. }
  88580. for (var attr in technique.attributes) {
  88581. var attribute = technique.attributes[attr];
  88582. var attributeParameter = technique.parameters[attribute];
  88583. if (attributeParameter.semantic) {
  88584. attributes.push(getAttribute(attributeParameter));
  88585. }
  88586. }
  88587. // Configure vertex shader
  88588. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  88589. var tokenType = vertexTokenizer.currentToken;
  88590. if (tokenType !== ETokenType.IDENTIFIER) {
  88591. newVertexShader += vertexTokenizer.currentString;
  88592. continue;
  88593. }
  88594. var foundAttribute = false;
  88595. for (var attr in technique.attributes) {
  88596. var attribute = technique.attributes[attr];
  88597. var attributeParameter = technique.parameters[attribute];
  88598. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  88599. newVertexShader += getAttribute(attributeParameter);
  88600. foundAttribute = true;
  88601. break;
  88602. }
  88603. }
  88604. if (foundAttribute) {
  88605. continue;
  88606. }
  88607. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  88608. }
  88609. // Configure pixel shader
  88610. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  88611. var tokenType = pixelTokenizer.currentToken;
  88612. if (tokenType !== ETokenType.IDENTIFIER) {
  88613. newPixelShader += pixelTokenizer.currentString;
  88614. continue;
  88615. }
  88616. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  88617. }
  88618. // Create shader material
  88619. var shaderPath = {
  88620. vertex: program.vertexShader + id,
  88621. fragment: program.fragmentShader + id
  88622. };
  88623. var options = {
  88624. attributes: attributes,
  88625. uniforms: uniforms,
  88626. samplers: samplers,
  88627. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  88628. };
  88629. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  88630. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  88631. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  88632. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  88633. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  88634. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  88635. if (states && states.functions) {
  88636. var functions = states.functions;
  88637. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  88638. shaderMaterial.backFaceCulling = false;
  88639. }
  88640. var blendFunc = functions.blendFuncSeparate;
  88641. if (blendFunc) {
  88642. 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) {
  88643. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  88644. }
  88645. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  88646. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  88647. }
  88648. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  88649. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  88650. }
  88651. 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) {
  88652. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  88653. }
  88654. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  88655. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  88656. }
  88657. 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) {
  88658. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  88659. }
  88660. }
  88661. }
  88662. };
  88663. return GLTFLoaderBase;
  88664. }());
  88665. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  88666. /**
  88667. * glTF V1 Loader
  88668. */
  88669. var GLTFLoader = /** @class */ (function () {
  88670. function GLTFLoader() {
  88671. // #region Stubs for IGLTFLoader interface
  88672. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  88673. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  88674. this.compileMaterials = false;
  88675. this.useClipPlane = false;
  88676. this.compileShadowGenerators = false;
  88677. this.onDisposeObservable = new BABYLON.Observable();
  88678. this.onMeshLoadedObservable = new BABYLON.Observable();
  88679. this.onTextureLoadedObservable = new BABYLON.Observable();
  88680. this.onMaterialLoadedObservable = new BABYLON.Observable();
  88681. this.onCompleteObservable = new BABYLON.Observable();
  88682. }
  88683. GLTFLoader.RegisterExtension = function (extension) {
  88684. if (GLTFLoader.Extensions[extension.name]) {
  88685. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  88686. return;
  88687. }
  88688. GLTFLoader.Extensions[extension.name] = extension;
  88689. };
  88690. GLTFLoader.prototype.dispose = function () { };
  88691. // #endregion
  88692. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  88693. var _this = this;
  88694. scene.useRightHandedSystem = true;
  88695. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  88696. gltfRuntime.importOnlyMeshes = true;
  88697. if (meshesNames === "") {
  88698. gltfRuntime.importMeshesNames = [];
  88699. }
  88700. else if (typeof meshesNames === "string") {
  88701. gltfRuntime.importMeshesNames = [meshesNames];
  88702. }
  88703. else if (meshesNames && !(meshesNames instanceof Array)) {
  88704. gltfRuntime.importMeshesNames = [meshesNames];
  88705. }
  88706. else {
  88707. gltfRuntime.importMeshesNames = [];
  88708. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  88709. }
  88710. // Create nodes
  88711. _this._createNodes(gltfRuntime);
  88712. var meshes = new Array();
  88713. var skeletons = new Array();
  88714. // Fill arrays of meshes and skeletons
  88715. for (var nde in gltfRuntime.nodes) {
  88716. var node = gltfRuntime.nodes[nde];
  88717. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  88718. meshes.push(node.babylonNode);
  88719. }
  88720. }
  88721. for (var skl in gltfRuntime.skins) {
  88722. var skin = gltfRuntime.skins[skl];
  88723. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  88724. skeletons.push(skin.babylonSkeleton);
  88725. }
  88726. }
  88727. // Load buffers, shaders, materials, etc.
  88728. _this._loadBuffersAsync(gltfRuntime, function () {
  88729. _this._loadShadersAsync(gltfRuntime, function () {
  88730. importMaterials(gltfRuntime);
  88731. postLoad(gltfRuntime);
  88732. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  88733. onSuccess(meshes, [], skeletons);
  88734. }
  88735. });
  88736. }, onProgress);
  88737. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  88738. onSuccess(meshes, [], skeletons);
  88739. }
  88740. }, onError);
  88741. return true;
  88742. };
  88743. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  88744. var _this = this;
  88745. scene.useRightHandedSystem = true;
  88746. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  88747. // Load runtime extensios
  88748. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  88749. // Create nodes
  88750. _this._createNodes(gltfRuntime);
  88751. // Load buffers, shaders, materials, etc.
  88752. _this._loadBuffersAsync(gltfRuntime, function () {
  88753. _this._loadShadersAsync(gltfRuntime, function () {
  88754. importMaterials(gltfRuntime);
  88755. postLoad(gltfRuntime);
  88756. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  88757. onSuccess();
  88758. }
  88759. });
  88760. });
  88761. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  88762. onSuccess();
  88763. }
  88764. }, onError);
  88765. }, onError);
  88766. };
  88767. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  88768. var hasShaders = false;
  88769. var processShader = function (sha, shader) {
  88770. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  88771. gltfRuntime.loadedShaderCount++;
  88772. if (shaderString) {
  88773. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  88774. }
  88775. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  88776. onload();
  88777. }
  88778. }, function () {
  88779. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  88780. });
  88781. };
  88782. for (var sha in gltfRuntime.shaders) {
  88783. hasShaders = true;
  88784. var shader = gltfRuntime.shaders[sha];
  88785. if (shader) {
  88786. processShader.bind(this, sha, shader)();
  88787. }
  88788. else {
  88789. BABYLON.Tools.Error("No shader named: " + sha);
  88790. }
  88791. }
  88792. if (!hasShaders) {
  88793. onload();
  88794. }
  88795. };
  88796. ;
  88797. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  88798. var hasBuffers = false;
  88799. var processBuffer = function (buf, buffer) {
  88800. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  88801. gltfRuntime.loadedBufferCount++;
  88802. if (bufferView) {
  88803. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  88804. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  88805. }
  88806. gltfRuntime.loadedBufferViews[buf] = bufferView;
  88807. }
  88808. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  88809. onLoad();
  88810. }
  88811. }, function () {
  88812. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  88813. });
  88814. };
  88815. for (var buf in gltfRuntime.buffers) {
  88816. hasBuffers = true;
  88817. var buffer = gltfRuntime.buffers[buf];
  88818. if (buffer) {
  88819. processBuffer.bind(this, buf, buffer)();
  88820. }
  88821. else {
  88822. BABYLON.Tools.Error("No buffer named: " + buf);
  88823. }
  88824. }
  88825. if (!hasBuffers) {
  88826. onLoad();
  88827. }
  88828. };
  88829. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  88830. var currentScene = gltfRuntime.currentScene;
  88831. if (currentScene) {
  88832. // Only one scene even if multiple scenes are defined
  88833. for (var i = 0; i < currentScene.nodes.length; i++) {
  88834. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  88835. }
  88836. }
  88837. else {
  88838. // Load all scenes
  88839. for (var thing in gltfRuntime.scenes) {
  88840. currentScene = gltfRuntime.scenes[thing];
  88841. for (var i = 0; i < currentScene.nodes.length; i++) {
  88842. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  88843. }
  88844. }
  88845. }
  88846. };
  88847. GLTFLoader.Extensions = {};
  88848. return GLTFLoader;
  88849. }());
  88850. GLTF1.GLTFLoader = GLTFLoader;
  88851. ;
  88852. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  88853. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  88854. })(BABYLON || (BABYLON = {}));
  88855. //# sourceMappingURL=babylon.glTFLoader.js.map
  88856. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88857. var BABYLON;
  88858. (function (BABYLON) {
  88859. var GLTF1;
  88860. (function (GLTF1) {
  88861. /**
  88862. * Utils functions for GLTF
  88863. */
  88864. var GLTFUtils = /** @class */ (function () {
  88865. function GLTFUtils() {
  88866. }
  88867. /**
  88868. * Sets the given "parameter" matrix
  88869. * @param scene: the {BABYLON.Scene} object
  88870. * @param source: the source node where to pick the matrix
  88871. * @param parameter: the GLTF technique parameter
  88872. * @param uniformName: the name of the shader's uniform
  88873. * @param shaderMaterial: the shader material
  88874. */
  88875. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  88876. var mat = null;
  88877. if (parameter.semantic === "MODEL") {
  88878. mat = source.getWorldMatrix();
  88879. }
  88880. else if (parameter.semantic === "PROJECTION") {
  88881. mat = scene.getProjectionMatrix();
  88882. }
  88883. else if (parameter.semantic === "VIEW") {
  88884. mat = scene.getViewMatrix();
  88885. }
  88886. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  88887. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  88888. }
  88889. else if (parameter.semantic === "MODELVIEW") {
  88890. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  88891. }
  88892. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  88893. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  88894. }
  88895. else if (parameter.semantic === "MODELINVERSE") {
  88896. mat = source.getWorldMatrix().invert();
  88897. }
  88898. else if (parameter.semantic === "VIEWINVERSE") {
  88899. mat = scene.getViewMatrix().invert();
  88900. }
  88901. else if (parameter.semantic === "PROJECTIONINVERSE") {
  88902. mat = scene.getProjectionMatrix().invert();
  88903. }
  88904. else if (parameter.semantic === "MODELVIEWINVERSE") {
  88905. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  88906. }
  88907. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  88908. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  88909. }
  88910. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  88911. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  88912. }
  88913. else {
  88914. debugger;
  88915. }
  88916. if (mat) {
  88917. switch (parameter.type) {
  88918. case GLTF1.EParameterType.FLOAT_MAT2:
  88919. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  88920. break;
  88921. case GLTF1.EParameterType.FLOAT_MAT3:
  88922. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  88923. break;
  88924. case GLTF1.EParameterType.FLOAT_MAT4:
  88925. shaderMaterial.setMatrix(uniformName, mat);
  88926. break;
  88927. default: break;
  88928. }
  88929. }
  88930. };
  88931. /**
  88932. * Sets the given "parameter" matrix
  88933. * @param shaderMaterial: the shader material
  88934. * @param uniform: the name of the shader's uniform
  88935. * @param value: the value of the uniform
  88936. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  88937. */
  88938. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  88939. switch (type) {
  88940. case GLTF1.EParameterType.FLOAT:
  88941. shaderMaterial.setFloat(uniform, value);
  88942. return true;
  88943. case GLTF1.EParameterType.FLOAT_VEC2:
  88944. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  88945. return true;
  88946. case GLTF1.EParameterType.FLOAT_VEC3:
  88947. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  88948. return true;
  88949. case GLTF1.EParameterType.FLOAT_VEC4:
  88950. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  88951. return true;
  88952. default: return false;
  88953. }
  88954. };
  88955. /**
  88956. * If the uri is a base64 string
  88957. * @param uri: the uri to test
  88958. */
  88959. GLTFUtils.IsBase64 = function (uri) {
  88960. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  88961. };
  88962. /**
  88963. * Decode the base64 uri
  88964. * @param uri: the uri to decode
  88965. */
  88966. GLTFUtils.DecodeBase64 = function (uri) {
  88967. var decodedString = atob(uri.split(",")[1]);
  88968. var bufferLength = decodedString.length;
  88969. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  88970. for (var i = 0; i < bufferLength; i++) {
  88971. bufferView[i] = decodedString.charCodeAt(i);
  88972. }
  88973. return bufferView.buffer;
  88974. };
  88975. /**
  88976. * Returns the wrap mode of the texture
  88977. * @param mode: the mode value
  88978. */
  88979. GLTFUtils.GetWrapMode = function (mode) {
  88980. switch (mode) {
  88981. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  88982. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  88983. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  88984. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  88985. }
  88986. };
  88987. /**
  88988. * Returns the byte stride giving an accessor
  88989. * @param accessor: the GLTF accessor objet
  88990. */
  88991. GLTFUtils.GetByteStrideFromType = function (accessor) {
  88992. // Needs this function since "byteStride" isn't requiered in glTF format
  88993. var type = accessor.type;
  88994. switch (type) {
  88995. case "VEC2": return 2;
  88996. case "VEC3": return 3;
  88997. case "VEC4": return 4;
  88998. case "MAT2": return 4;
  88999. case "MAT3": return 9;
  89000. case "MAT4": return 16;
  89001. default: return 1;
  89002. }
  89003. };
  89004. /**
  89005. * Returns the texture filter mode giving a mode value
  89006. * @param mode: the filter mode value
  89007. */
  89008. GLTFUtils.GetTextureFilterMode = function (mode) {
  89009. switch (mode) {
  89010. case GLTF1.ETextureFilterType.LINEAR:
  89011. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  89012. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  89013. case GLTF1.ETextureFilterType.NEAREST:
  89014. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  89015. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  89016. }
  89017. };
  89018. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  89019. var byteOffset = bufferView.byteOffset + byteOffset;
  89020. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  89021. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  89022. throw new Error("Buffer access is out of range");
  89023. }
  89024. var buffer = loadedBufferView.buffer;
  89025. byteOffset += loadedBufferView.byteOffset;
  89026. switch (componentType) {
  89027. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  89028. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  89029. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  89030. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  89031. default: return new Float32Array(buffer, byteOffset, byteLength);
  89032. }
  89033. };
  89034. /**
  89035. * Returns a buffer from its accessor
  89036. * @param gltfRuntime: the GLTF runtime
  89037. * @param accessor: the GLTF accessor
  89038. */
  89039. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  89040. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  89041. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  89042. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  89043. };
  89044. /**
  89045. * Decodes a buffer view into a string
  89046. * @param view: the buffer view
  89047. */
  89048. GLTFUtils.DecodeBufferToText = function (view) {
  89049. var result = "";
  89050. var length = view.byteLength;
  89051. for (var i = 0; i < length; ++i) {
  89052. result += String.fromCharCode(view[i]);
  89053. }
  89054. return result;
  89055. };
  89056. /**
  89057. * Returns the default material of gltf. Related to
  89058. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  89059. * @param scene: the Babylon.js scene
  89060. */
  89061. GLTFUtils.GetDefaultMaterial = function (scene) {
  89062. if (!GLTFUtils._DefaultMaterial) {
  89063. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  89064. "precision highp float;",
  89065. "",
  89066. "uniform mat4 worldView;",
  89067. "uniform mat4 projection;",
  89068. "",
  89069. "attribute vec3 position;",
  89070. "",
  89071. "void main(void)",
  89072. "{",
  89073. " gl_Position = projection * worldView * vec4(position, 1.0);",
  89074. "}"
  89075. ].join("\n");
  89076. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  89077. "precision highp float;",
  89078. "",
  89079. "uniform vec4 u_emission;",
  89080. "",
  89081. "void main(void)",
  89082. "{",
  89083. " gl_FragColor = u_emission;",
  89084. "}"
  89085. ].join("\n");
  89086. var shaderPath = {
  89087. vertex: "GLTFDefaultMaterial",
  89088. fragment: "GLTFDefaultMaterial"
  89089. };
  89090. var options = {
  89091. attributes: ["position"],
  89092. uniforms: ["worldView", "projection", "u_emission"],
  89093. samplers: new Array(),
  89094. needAlphaBlending: false
  89095. };
  89096. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  89097. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  89098. }
  89099. return GLTFUtils._DefaultMaterial;
  89100. };
  89101. // The GLTF default material
  89102. GLTFUtils._DefaultMaterial = null;
  89103. return GLTFUtils;
  89104. }());
  89105. GLTF1.GLTFUtils = GLTFUtils;
  89106. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  89107. })(BABYLON || (BABYLON = {}));
  89108. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  89109. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  89110. var BABYLON;
  89111. (function (BABYLON) {
  89112. var GLTF1;
  89113. (function (GLTF1) {
  89114. var GLTFLoaderExtension = /** @class */ (function () {
  89115. function GLTFLoaderExtension(name) {
  89116. this._name = name;
  89117. }
  89118. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  89119. get: function () {
  89120. return this._name;
  89121. },
  89122. enumerable: true,
  89123. configurable: true
  89124. });
  89125. /**
  89126. * Defines an override for loading the runtime
  89127. * Return true to stop further extensions from loading the runtime
  89128. */
  89129. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  89130. return false;
  89131. };
  89132. /**
  89133. * Defines an onverride for creating gltf runtime
  89134. * Return true to stop further extensions from creating the runtime
  89135. */
  89136. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  89137. return false;
  89138. };
  89139. /**
  89140. * Defines an override for loading buffers
  89141. * Return true to stop further extensions from loading this buffer
  89142. */
  89143. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  89144. return false;
  89145. };
  89146. /**
  89147. * Defines an override for loading texture buffers
  89148. * Return true to stop further extensions from loading this texture data
  89149. */
  89150. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  89151. return false;
  89152. };
  89153. /**
  89154. * Defines an override for creating textures
  89155. * Return true to stop further extensions from loading this texture
  89156. */
  89157. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  89158. return false;
  89159. };
  89160. /**
  89161. * Defines an override for loading shader strings
  89162. * Return true to stop further extensions from loading this shader data
  89163. */
  89164. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  89165. return false;
  89166. };
  89167. /**
  89168. * Defines an override for loading materials
  89169. * Return true to stop further extensions from loading this material
  89170. */
  89171. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  89172. return false;
  89173. };
  89174. // ---------
  89175. // Utilities
  89176. // ---------
  89177. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  89178. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  89179. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  89180. }, function () {
  89181. setTimeout(function () {
  89182. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  89183. });
  89184. });
  89185. };
  89186. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  89187. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  89188. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  89189. }, function () {
  89190. setTimeout(function () {
  89191. onSuccess();
  89192. });
  89193. });
  89194. };
  89195. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  89196. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  89197. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  89198. }, function () {
  89199. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  89200. });
  89201. };
  89202. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  89203. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  89204. };
  89205. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  89206. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  89207. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  89208. }, function () {
  89209. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  89210. });
  89211. };
  89212. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  89213. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  89214. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  89215. }, function () {
  89216. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  89217. });
  89218. };
  89219. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  89220. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  89221. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  89222. }, function () {
  89223. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  89224. });
  89225. };
  89226. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  89227. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  89228. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  89229. }, function () {
  89230. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  89231. });
  89232. };
  89233. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  89234. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  89235. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  89236. if (func(loaderExtension)) {
  89237. return;
  89238. }
  89239. }
  89240. defaultFunc();
  89241. };
  89242. return GLTFLoaderExtension;
  89243. }());
  89244. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  89245. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  89246. })(BABYLON || (BABYLON = {}));
  89247. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  89248. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  89249. var BABYLON;
  89250. (function (BABYLON) {
  89251. var GLTF1;
  89252. (function (GLTF1) {
  89253. var BinaryExtensionBufferName = "binary_glTF";
  89254. ;
  89255. ;
  89256. var GLTFBinaryExtension = /** @class */ (function (_super) {
  89257. __extends(GLTFBinaryExtension, _super);
  89258. function GLTFBinaryExtension() {
  89259. return _super.call(this, "KHR_binary_glTF") || this;
  89260. }
  89261. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  89262. var extensionsUsed = data.json.extensionsUsed;
  89263. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  89264. return false;
  89265. }
  89266. this._bin = data.bin;
  89267. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  89268. return true;
  89269. };
  89270. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  89271. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  89272. return false;
  89273. }
  89274. if (id !== BinaryExtensionBufferName) {
  89275. return false;
  89276. }
  89277. onSuccess(this._bin);
  89278. return true;
  89279. };
  89280. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  89281. var texture = gltfRuntime.textures[id];
  89282. var source = gltfRuntime.images[texture.source];
  89283. if (!source.extensions || !(this.name in source.extensions)) {
  89284. return false;
  89285. }
  89286. var sourceExt = source.extensions[this.name];
  89287. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  89288. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  89289. onSuccess(buffer);
  89290. return true;
  89291. };
  89292. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  89293. var shader = gltfRuntime.shaders[id];
  89294. if (!shader.extensions || !(this.name in shader.extensions)) {
  89295. return false;
  89296. }
  89297. var binaryExtensionShader = shader.extensions[this.name];
  89298. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  89299. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  89300. setTimeout(function () {
  89301. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  89302. onSuccess(shaderString);
  89303. });
  89304. return true;
  89305. };
  89306. return GLTFBinaryExtension;
  89307. }(GLTF1.GLTFLoaderExtension));
  89308. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  89309. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  89310. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  89311. })(BABYLON || (BABYLON = {}));
  89312. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  89313. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  89314. var BABYLON;
  89315. (function (BABYLON) {
  89316. var GLTF1;
  89317. (function (GLTF1) {
  89318. ;
  89319. ;
  89320. ;
  89321. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  89322. __extends(GLTFMaterialsCommonExtension, _super);
  89323. function GLTFMaterialsCommonExtension() {
  89324. return _super.call(this, "KHR_materials_common") || this;
  89325. }
  89326. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  89327. if (!gltfRuntime.extensions)
  89328. return false;
  89329. var extension = gltfRuntime.extensions[this.name];
  89330. if (!extension)
  89331. return false;
  89332. // Create lights
  89333. var lights = extension.lights;
  89334. if (lights) {
  89335. for (var thing in lights) {
  89336. var light = lights[thing];
  89337. switch (light.type) {
  89338. case "ambient":
  89339. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  89340. var ambient = light.ambient;
  89341. if (ambient) {
  89342. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  89343. }
  89344. break;
  89345. case "point":
  89346. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  89347. var point = light.point;
  89348. if (point) {
  89349. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  89350. }
  89351. break;
  89352. case "directional":
  89353. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  89354. var directional = light.directional;
  89355. if (directional) {
  89356. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  89357. }
  89358. break;
  89359. case "spot":
  89360. var spot = light.spot;
  89361. if (spot) {
  89362. 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);
  89363. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  89364. }
  89365. break;
  89366. default:
  89367. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  89368. break;
  89369. }
  89370. }
  89371. }
  89372. return false;
  89373. };
  89374. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  89375. var material = gltfRuntime.materials[id];
  89376. if (!material || !material.extensions)
  89377. return false;
  89378. var extension = material.extensions[this.name];
  89379. if (!extension)
  89380. return false;
  89381. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  89382. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  89383. if (extension.technique === "CONSTANT") {
  89384. standardMaterial.disableLighting = true;
  89385. }
  89386. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  89387. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  89388. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  89389. // Ambient
  89390. if (typeof extension.values.ambient === "string") {
  89391. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  89392. }
  89393. else {
  89394. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  89395. }
  89396. // Diffuse
  89397. if (typeof extension.values.diffuse === "string") {
  89398. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  89399. }
  89400. else {
  89401. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  89402. }
  89403. // Emission
  89404. if (typeof extension.values.emission === "string") {
  89405. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  89406. }
  89407. else {
  89408. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  89409. }
  89410. // Specular
  89411. if (typeof extension.values.specular === "string") {
  89412. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  89413. }
  89414. else {
  89415. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  89416. }
  89417. return true;
  89418. };
  89419. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  89420. // Create buffer from texture url
  89421. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  89422. // Create texture from buffer
  89423. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  89424. }, onError);
  89425. };
  89426. return GLTFMaterialsCommonExtension;
  89427. }(GLTF1.GLTFLoaderExtension));
  89428. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  89429. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  89430. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  89431. })(BABYLON || (BABYLON = {}));
  89432. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  89433. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  89434. var BABYLON;
  89435. (function (BABYLON) {
  89436. var GLTF2;
  89437. (function (GLTF2) {
  89438. /**
  89439. * Enums
  89440. */
  89441. var EComponentType;
  89442. (function (EComponentType) {
  89443. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  89444. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  89445. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  89446. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  89447. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  89448. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  89449. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  89450. var EMeshPrimitiveMode;
  89451. (function (EMeshPrimitiveMode) {
  89452. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  89453. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  89454. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  89455. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  89456. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  89457. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  89458. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  89459. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  89460. var ETextureMagFilter;
  89461. (function (ETextureMagFilter) {
  89462. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  89463. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  89464. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  89465. var ETextureMinFilter;
  89466. (function (ETextureMinFilter) {
  89467. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  89468. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  89469. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  89470. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  89471. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  89472. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  89473. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  89474. var ETextureWrapMode;
  89475. (function (ETextureWrapMode) {
  89476. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  89477. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  89478. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  89479. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  89480. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  89481. })(BABYLON || (BABYLON = {}));
  89482. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  89483. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  89484. var BABYLON;
  89485. (function (BABYLON) {
  89486. var GLTF2;
  89487. (function (GLTF2) {
  89488. var GLTFLoaderTracker = /** @class */ (function () {
  89489. function GLTFLoaderTracker(onComplete) {
  89490. this._pendingCount = 0;
  89491. this._callback = onComplete;
  89492. }
  89493. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  89494. this._pendingCount++;
  89495. };
  89496. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  89497. if (--this._pendingCount === 0) {
  89498. this._callback();
  89499. }
  89500. };
  89501. return GLTFLoaderTracker;
  89502. }());
  89503. var GLTFLoader = /** @class */ (function () {
  89504. function GLTFLoader() {
  89505. this._disposed = false;
  89506. this._defaultSampler = {};
  89507. this._renderReady = false;
  89508. this._requests = new Array();
  89509. this._renderReadyObservable = new BABYLON.Observable();
  89510. // Count of pending work that needs to complete before the asset is rendered.
  89511. this._renderPendingCount = 0;
  89512. // Count of pending work that needs to complete before the loader is disposed.
  89513. this._loaderPendingCount = 0;
  89514. this._loaderTrackers = new Array();
  89515. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  89516. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  89517. this.compileMaterials = false;
  89518. this.useClipPlane = false;
  89519. this.compileShadowGenerators = false;
  89520. this.onDisposeObservable = new BABYLON.Observable();
  89521. this.onMeshLoadedObservable = new BABYLON.Observable();
  89522. this.onTextureLoadedObservable = new BABYLON.Observable();
  89523. this.onMaterialLoadedObservable = new BABYLON.Observable();
  89524. this.onCompleteObservable = new BABYLON.Observable();
  89525. }
  89526. GLTFLoader.RegisterExtension = function (extension) {
  89527. if (GLTFLoader.Extensions[extension.name]) {
  89528. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  89529. return;
  89530. }
  89531. GLTFLoader.Extensions[extension.name] = extension;
  89532. // Keep the order of registration so that extensions registered first are called first.
  89533. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  89534. };
  89535. GLTFLoader.prototype.dispose = function () {
  89536. if (this._disposed) {
  89537. return;
  89538. }
  89539. this._disposed = true;
  89540. this._abortRequests();
  89541. this._releaseResources();
  89542. this.onDisposeObservable.notifyObservers(this);
  89543. };
  89544. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  89545. var _this = this;
  89546. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  89547. if (onSuccess) {
  89548. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  89549. }
  89550. }, onProgress, onError);
  89551. };
  89552. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  89553. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  89554. };
  89555. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  89556. var _this = this;
  89557. this._babylonScene = scene;
  89558. this._rootUrl = rootUrl;
  89559. this._successCallback = onSuccess;
  89560. this._progressCallback = onProgress;
  89561. this._errorCallback = onError;
  89562. this._tryCatchOnError(function () {
  89563. _this._loadData(data);
  89564. _this._addPendingData(_this);
  89565. _this._loadDefaultScene(nodeNames);
  89566. _this._loadAnimations();
  89567. _this._removePendingData(_this);
  89568. });
  89569. };
  89570. GLTFLoader.prototype._onProgress = function () {
  89571. if (!this._progressCallback) {
  89572. return;
  89573. }
  89574. var lengthComputable = true;
  89575. var loaded = 0;
  89576. var total = 0;
  89577. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  89578. var request = _a[_i];
  89579. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  89580. return;
  89581. }
  89582. lengthComputable = lengthComputable && request._lengthComputable;
  89583. loaded += request._loaded;
  89584. total += request._total;
  89585. }
  89586. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  89587. };
  89588. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  89589. if (this._renderReady) {
  89590. func();
  89591. }
  89592. else {
  89593. this._renderReadyObservable.add(func);
  89594. }
  89595. };
  89596. GLTFLoader.prototype._onRenderReady = function () {
  89597. this._rootNode.babylonMesh.setEnabled(true);
  89598. this._startAnimations();
  89599. if (this._successCallback) {
  89600. this._successCallback();
  89601. }
  89602. this._renderReadyObservable.notifyObservers(this);
  89603. };
  89604. GLTFLoader.prototype._onComplete = function () {
  89605. this._abortRequests();
  89606. this._releaseResources();
  89607. this.onCompleteObservable.notifyObservers(this);
  89608. };
  89609. GLTFLoader.prototype._loadData = function (data) {
  89610. this._gltf = data.json;
  89611. // Assign the index of each object for convinience.
  89612. GLTFLoader._AssignIndices(this._gltf.accessors);
  89613. GLTFLoader._AssignIndices(this._gltf.animations);
  89614. GLTFLoader._AssignIndices(this._gltf.buffers);
  89615. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  89616. GLTFLoader._AssignIndices(this._gltf.images);
  89617. GLTFLoader._AssignIndices(this._gltf.materials);
  89618. GLTFLoader._AssignIndices(this._gltf.meshes);
  89619. GLTFLoader._AssignIndices(this._gltf.nodes);
  89620. GLTFLoader._AssignIndices(this._gltf.samplers);
  89621. GLTFLoader._AssignIndices(this._gltf.scenes);
  89622. GLTFLoader._AssignIndices(this._gltf.skins);
  89623. GLTFLoader._AssignIndices(this._gltf.textures);
  89624. // Handle global extensions as they may add their own data types.
  89625. GLTF2.GLTFLoaderExtension.LoadRoot(this, "#/", this._gltf);
  89626. if (data.bin) {
  89627. var buffers = this._gltf.buffers;
  89628. if (buffers && buffers[0] && !buffers[0].uri) {
  89629. var binaryBuffer = buffers[0];
  89630. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  89631. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  89632. }
  89633. binaryBuffer.loadedData = data.bin;
  89634. }
  89635. else {
  89636. BABYLON.Tools.Warn("Unexpected BIN chunk");
  89637. }
  89638. }
  89639. };
  89640. GLTFLoader.prototype._getMeshes = function () {
  89641. var meshes = new Array();
  89642. // Root mesh is always first.
  89643. meshes.push(this._rootNode.babylonMesh);
  89644. var nodes = this._gltf.nodes;
  89645. if (nodes) {
  89646. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  89647. var node = nodes_1[_i];
  89648. if (node.babylonMesh) {
  89649. meshes.push(node.babylonMesh);
  89650. }
  89651. }
  89652. }
  89653. return meshes;
  89654. };
  89655. GLTFLoader.prototype._getSkeletons = function () {
  89656. var skeletons = new Array();
  89657. var skins = this._gltf.skins;
  89658. if (skins) {
  89659. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  89660. var skin = skins_1[_i];
  89661. if (skin.babylonSkeleton) {
  89662. skeletons.push(skin.babylonSkeleton);
  89663. }
  89664. }
  89665. }
  89666. return skeletons;
  89667. };
  89668. GLTFLoader.prototype._startAnimations = function () {
  89669. var animations = this._gltf.animations;
  89670. if (!animations) {
  89671. return;
  89672. }
  89673. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  89674. var animation = animations_1[_i];
  89675. animation.babylonAnimationGroup.normalize();
  89676. }
  89677. switch (this.animationStartMode) {
  89678. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  89679. // do nothing
  89680. break;
  89681. }
  89682. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  89683. var animation = animations[0];
  89684. animation.babylonAnimationGroup.start(true);
  89685. break;
  89686. }
  89687. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  89688. for (var _a = 0, animations_2 = animations; _a < animations_2.length; _a++) {
  89689. var animation = animations_2[_a];
  89690. animation.babylonAnimationGroup.start(true);
  89691. }
  89692. break;
  89693. }
  89694. default: {
  89695. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  89696. return;
  89697. }
  89698. }
  89699. };
  89700. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  89701. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  89702. if (!scene) {
  89703. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  89704. }
  89705. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  89706. };
  89707. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  89708. var _this = this;
  89709. GLTF2.GLTFLoaderExtension.LoadScene(this, context, scene);
  89710. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  89711. switch (this.coordinateSystemMode) {
  89712. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  89713. if (!this._babylonScene.useRightHandedSystem) {
  89714. this._rootNode.rotation = [0, 1, 0, 0];
  89715. this._rootNode.scale = [1, 1, -1];
  89716. this._loadTransform(this._rootNode);
  89717. }
  89718. break;
  89719. }
  89720. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  89721. this._babylonScene.useRightHandedSystem = true;
  89722. break;
  89723. }
  89724. default: {
  89725. BABYLON.Tools.Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  89726. return;
  89727. }
  89728. }
  89729. this.onMeshLoadedObservable.notifyObservers(this._rootNode.babylonMesh);
  89730. var nodeIndices = scene.nodes;
  89731. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  89732. node.parent = parentNode;
  89733. return true;
  89734. }, this._rootNode);
  89735. if (nodeNames) {
  89736. if (!(nodeNames instanceof Array)) {
  89737. nodeNames = [nodeNames];
  89738. }
  89739. var filteredNodeIndices_1 = new Array();
  89740. this._traverseNodes(context, nodeIndices, function (node) {
  89741. if (nodeNames.indexOf(node.name) !== -1) {
  89742. filteredNodeIndices_1.push(node.index);
  89743. node.parent = _this._rootNode;
  89744. return false;
  89745. }
  89746. return true;
  89747. }, this._rootNode);
  89748. nodeIndices = filteredNodeIndices_1;
  89749. }
  89750. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  89751. var index = nodeIndices_1[_i];
  89752. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  89753. if (!node) {
  89754. throw new Error(context + ": Failed to find node " + index);
  89755. }
  89756. this._loadNode("#/nodes/" + index, node);
  89757. }
  89758. // Disable the root mesh until the asset is ready to render.
  89759. this._rootNode.babylonMesh.setEnabled(false);
  89760. };
  89761. GLTFLoader.prototype._loadNode = function (context, node) {
  89762. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  89763. return;
  89764. }
  89765. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  89766. this._loadTransform(node);
  89767. if (node.mesh != null) {
  89768. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  89769. if (!mesh) {
  89770. throw new Error(context + ": Failed to find mesh " + node.mesh);
  89771. }
  89772. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  89773. }
  89774. node.babylonMesh.parent = node.parent.babylonMesh;
  89775. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  89776. node.babylonAnimationTargets.push(node.babylonMesh);
  89777. if (node.skin != null) {
  89778. var skin_1 = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  89779. if (!skin_1) {
  89780. throw new Error(context + ": Failed to find skin " + node.skin);
  89781. }
  89782. this._loadSkinAsync("#/skins/" + node.skin, skin_1, function () {
  89783. node.babylonMesh.skeleton = skin_1.babylonSkeleton;
  89784. node.babylonMesh._refreshBoundingInfo(true);
  89785. });
  89786. node.babylonMesh.parent = this._rootNode.babylonMesh;
  89787. node.babylonMesh.position = BABYLON.Vector3.Zero();
  89788. node.babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  89789. node.babylonMesh.scaling = BABYLON.Vector3.One();
  89790. }
  89791. if (node.camera != null) {
  89792. // TODO: handle cameras
  89793. }
  89794. if (node.children) {
  89795. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  89796. var index = _a[_i];
  89797. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  89798. if (!childNode) {
  89799. throw new Error(context + ": Failed to find child node " + index);
  89800. }
  89801. this._loadNode("#/nodes/" + index, childNode);
  89802. }
  89803. }
  89804. this.onMeshLoadedObservable.notifyObservers(node.babylonMesh);
  89805. };
  89806. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  89807. var _this = this;
  89808. var primitives = mesh.primitives;
  89809. if (!primitives || primitives.length === 0) {
  89810. throw new Error(context + ": Primitives are missing");
  89811. }
  89812. this._createMorphTargets(context, node, mesh);
  89813. this._loadAllVertexDataAsync(context, mesh, function () {
  89814. _this._loadMorphTargets(context, node, mesh);
  89815. var vertexData = new BABYLON.VertexData();
  89816. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  89817. var primitive = primitives_1[_i];
  89818. vertexData.merge(primitive.vertexData);
  89819. }
  89820. node.babylonMesh.hasVertexAlpha = mesh.hasVertexAlpha;
  89821. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  89822. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  89823. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  89824. node.babylonMesh.subMeshes = [];
  89825. var verticesStart = 0;
  89826. var indicesStart = 0;
  89827. for (var index = 0; index < primitives.length; index++) {
  89828. var vertexData_1 = primitives[index].vertexData;
  89829. var verticesCount = vertexData_1.positions.length;
  89830. var indicesCount = vertexData_1.indices.length;
  89831. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  89832. verticesStart += verticesCount;
  89833. indicesStart += indicesCount;
  89834. }
  89835. ;
  89836. });
  89837. if (primitives.length === 1) {
  89838. var primitive = primitives[0];
  89839. if (primitive.material == null) {
  89840. node.babylonMesh.material = this._getDefaultMaterial();
  89841. }
  89842. else {
  89843. var material = GLTFLoader._GetProperty(this._gltf.materials, primitive.material);
  89844. if (!material) {
  89845. throw new Error(context + ": Failed to find material " + primitive.material);
  89846. }
  89847. this._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  89848. if (isNew) {
  89849. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  89850. }
  89851. node.babylonMesh.material = babylonMaterial;
  89852. });
  89853. }
  89854. }
  89855. else {
  89856. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  89857. node.babylonMesh.material = multiMaterial;
  89858. var subMaterials_1 = multiMaterial.subMaterials;
  89859. var _loop_1 = function (index) {
  89860. var primitive = primitives[index];
  89861. if (primitive.material == null) {
  89862. subMaterials_1[index] = this_1._getDefaultMaterial();
  89863. }
  89864. else {
  89865. var material = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  89866. if (!material) {
  89867. throw new Error(context + ": Failed to find material " + primitive.material);
  89868. }
  89869. this_1._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  89870. if (isNew) {
  89871. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  89872. }
  89873. subMaterials_1[index] = babylonMaterial;
  89874. });
  89875. }
  89876. };
  89877. var this_1 = this;
  89878. for (var index = 0; index < primitives.length; index++) {
  89879. _loop_1(index);
  89880. }
  89881. ;
  89882. }
  89883. };
  89884. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  89885. var primitives = mesh.primitives;
  89886. var numRemainingPrimitives = primitives.length;
  89887. var _loop_2 = function (index) {
  89888. var primitive = primitives[index];
  89889. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  89890. primitive.vertexData = vertexData;
  89891. if (--numRemainingPrimitives === 0) {
  89892. onSuccess();
  89893. }
  89894. });
  89895. };
  89896. var this_2 = this;
  89897. for (var index = 0; index < primitives.length; index++) {
  89898. _loop_2(index);
  89899. }
  89900. };
  89901. /**
  89902. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  89903. * @param {ArrayBufferView} data
  89904. * @param {IGLTFAccessor} accessor
  89905. */
  89906. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  89907. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  89908. return data;
  89909. }
  89910. var buffer = data;
  89911. var factor = 1;
  89912. switch (accessor.componentType) {
  89913. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  89914. factor = 1 / 255;
  89915. break;
  89916. }
  89917. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  89918. factor = 1 / 65535;
  89919. break;
  89920. }
  89921. default: {
  89922. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  89923. }
  89924. }
  89925. var result = new Float32Array(accessor.count * 2);
  89926. for (var i = 0; i < result.length; ++i) {
  89927. result[i] = buffer[i] * factor;
  89928. }
  89929. return result;
  89930. };
  89931. /**
  89932. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  89933. * @param {ArrayBufferView} data
  89934. * @param {IGLTFAccessor} accessor
  89935. */
  89936. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  89937. var colorComponentCount = GLTFLoader._GetNumComponents(context, accessor.type);
  89938. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  89939. return data;
  89940. }
  89941. var buffer = data;
  89942. var factor = 1;
  89943. switch (accessor.componentType) {
  89944. case GLTF2.EComponentType.FLOAT: {
  89945. factor = 1;
  89946. break;
  89947. }
  89948. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  89949. factor = 1 / 255;
  89950. break;
  89951. }
  89952. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  89953. factor = 1 / 65535;
  89954. break;
  89955. }
  89956. default: {
  89957. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  89958. }
  89959. }
  89960. var result = new Float32Array(accessor.count * 4);
  89961. if (colorComponentCount === 4) {
  89962. for (var i = 0; i < result.length; ++i) {
  89963. result[i] = buffer[i] * factor;
  89964. }
  89965. }
  89966. else {
  89967. var offset = 0;
  89968. for (var i = 0; i < result.length; ++i) {
  89969. if ((i + 1) % 4 === 0) {
  89970. result[i] = 1;
  89971. }
  89972. else {
  89973. result[i] = buffer[offset++] * factor;
  89974. }
  89975. }
  89976. }
  89977. return result;
  89978. };
  89979. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  89980. var _this = this;
  89981. var attributes = primitive.attributes;
  89982. if (!attributes) {
  89983. throw new Error(context + ": Attributes are missing");
  89984. }
  89985. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  89986. // TODO: handle other primitive modes
  89987. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  89988. }
  89989. var vertexData = new BABYLON.VertexData();
  89990. var numRemainingAttributes = Object.keys(attributes).length;
  89991. var _loop_3 = function (attribute) {
  89992. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  89993. if (!accessor) {
  89994. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  89995. }
  89996. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  89997. switch (attribute) {
  89998. case "POSITION": {
  89999. vertexData.positions = data;
  90000. break;
  90001. }
  90002. case "NORMAL": {
  90003. vertexData.normals = data;
  90004. break;
  90005. }
  90006. case "TANGENT": {
  90007. vertexData.tangents = data;
  90008. break;
  90009. }
  90010. case "TEXCOORD_0": {
  90011. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  90012. break;
  90013. }
  90014. case "TEXCOORD_1": {
  90015. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  90016. break;
  90017. }
  90018. case "JOINTS_0": {
  90019. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  90020. break;
  90021. }
  90022. case "WEIGHTS_0": {
  90023. //TODO: need to add support for normalized weights.
  90024. vertexData.matricesWeights = data;
  90025. break;
  90026. }
  90027. case "COLOR_0": {
  90028. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  90029. var hasVertexAlpha = GLTFLoader._GetNumComponents(context, accessor.type) === 4;
  90030. if (!mesh.hasVertexAlpha && hasVertexAlpha) {
  90031. mesh.hasVertexAlpha = hasVertexAlpha;
  90032. }
  90033. break;
  90034. }
  90035. default: {
  90036. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  90037. break;
  90038. }
  90039. }
  90040. if (--numRemainingAttributes === 0) {
  90041. if (primitive.indices == null) {
  90042. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  90043. for (var i = 0; i < vertexData.indices.length; i++) {
  90044. vertexData.indices[i] = i;
  90045. }
  90046. onSuccess(vertexData);
  90047. }
  90048. else {
  90049. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  90050. if (!indicesAccessor) {
  90051. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  90052. }
  90053. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  90054. vertexData.indices = data;
  90055. onSuccess(vertexData);
  90056. });
  90057. }
  90058. }
  90059. });
  90060. };
  90061. var this_3 = this;
  90062. for (var attribute in attributes) {
  90063. _loop_3(attribute);
  90064. }
  90065. };
  90066. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  90067. var primitives = mesh.primitives;
  90068. var targets = primitives[0].targets;
  90069. if (!targets) {
  90070. return;
  90071. }
  90072. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  90073. var primitive = primitives_2[_i];
  90074. if (!primitive.targets || primitive.targets.length != targets.length) {
  90075. throw new Error(context + ": All primitives are required to list the same number of targets");
  90076. }
  90077. }
  90078. var morphTargetManager = new BABYLON.MorphTargetManager();
  90079. node.babylonMesh.morphTargetManager = morphTargetManager;
  90080. for (var index = 0; index < targets.length; index++) {
  90081. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  90082. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  90083. }
  90084. };
  90085. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  90086. var morphTargetManager = node.babylonMesh.morphTargetManager;
  90087. if (!morphTargetManager) {
  90088. return;
  90089. }
  90090. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  90091. var numTargets = morphTargetManager.numTargets;
  90092. for (var index = 0; index < numTargets; index++) {
  90093. var vertexData = new BABYLON.VertexData();
  90094. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  90095. var primitive = _a[_i];
  90096. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  90097. }
  90098. if (!vertexData.positions) {
  90099. throw new Error(context + ": Positions are missing");
  90100. }
  90101. var target = morphTargetManager.getTarget(index);
  90102. target.setPositions(vertexData.positions);
  90103. target.setNormals(vertexData.normals);
  90104. target.setTangents(vertexData.tangents);
  90105. }
  90106. });
  90107. };
  90108. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  90109. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  90110. var _loop_4 = function (primitive) {
  90111. var targets = primitive.targets;
  90112. primitive.targetsVertexData = new Array(targets.length);
  90113. var _loop_5 = function (index) {
  90114. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  90115. primitive.targetsVertexData[index] = vertexData;
  90116. if (--numRemainingTargets === 0) {
  90117. onSuccess();
  90118. }
  90119. });
  90120. };
  90121. for (var index = 0; index < targets.length; index++) {
  90122. _loop_5(index);
  90123. }
  90124. };
  90125. var this_4 = this;
  90126. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  90127. var primitive = _a[_i];
  90128. _loop_4(primitive);
  90129. }
  90130. };
  90131. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  90132. var targetVertexData = new BABYLON.VertexData();
  90133. var numRemainingAttributes = Object.keys(attributes).length;
  90134. var _loop_6 = function (attribute) {
  90135. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  90136. if (!accessor) {
  90137. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  90138. }
  90139. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  90140. // glTF stores morph target information as deltas while babylon.js expects the final data.
  90141. // As a result we have to add the original data to the delta to calculate the final data.
  90142. var values = data;
  90143. switch (attribute) {
  90144. case "POSITION": {
  90145. for (var i = 0; i < values.length; i++) {
  90146. values[i] += vertexData.positions[i];
  90147. }
  90148. targetVertexData.positions = values;
  90149. break;
  90150. }
  90151. case "NORMAL": {
  90152. for (var i = 0; i < values.length; i++) {
  90153. values[i] += vertexData.normals[i];
  90154. }
  90155. targetVertexData.normals = values;
  90156. break;
  90157. }
  90158. case "TANGENT": {
  90159. // Tangent data for morph targets is stored as xyz delta.
  90160. // The vertexData.tangent is stored as xyzw.
  90161. // So we need to skip every fourth vertexData.tangent.
  90162. for (var i = 0, j = 0; i < values.length; i++, j++) {
  90163. values[i] += vertexData.tangents[j];
  90164. if ((i + 1) % 3 == 0) {
  90165. j++;
  90166. }
  90167. }
  90168. targetVertexData.tangents = values;
  90169. break;
  90170. }
  90171. default: {
  90172. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  90173. break;
  90174. }
  90175. }
  90176. if (--numRemainingAttributes === 0) {
  90177. onSuccess(targetVertexData);
  90178. }
  90179. });
  90180. };
  90181. var this_5 = this;
  90182. for (var attribute in attributes) {
  90183. _loop_6(attribute);
  90184. }
  90185. };
  90186. GLTFLoader.prototype._loadTransform = function (node) {
  90187. var position = BABYLON.Vector3.Zero();
  90188. var rotation = BABYLON.Quaternion.Identity();
  90189. var scaling = BABYLON.Vector3.One();
  90190. if (node.matrix) {
  90191. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  90192. matrix.decompose(scaling, rotation, position);
  90193. }
  90194. else {
  90195. if (node.translation)
  90196. position = BABYLON.Vector3.FromArray(node.translation);
  90197. if (node.rotation)
  90198. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  90199. if (node.scale)
  90200. scaling = BABYLON.Vector3.FromArray(node.scale);
  90201. }
  90202. node.babylonMesh.position = position;
  90203. node.babylonMesh.rotationQuaternion = rotation;
  90204. node.babylonMesh.scaling = scaling;
  90205. };
  90206. GLTFLoader.prototype._loadSkinAsync = function (context, skin, onSuccess) {
  90207. var _this = this;
  90208. if (skin.babylonSkeleton) {
  90209. onSuccess();
  90210. return;
  90211. }
  90212. var skeletonId = "skeleton" + skin.index;
  90213. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  90214. if (skin.inverseBindMatrices == null) {
  90215. this._loadBones(context, skin, null);
  90216. onSuccess();
  90217. }
  90218. else {
  90219. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  90220. if (!accessor) {
  90221. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  90222. }
  90223. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  90224. _this._loadBones(context, skin, data);
  90225. onSuccess();
  90226. });
  90227. }
  90228. };
  90229. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  90230. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  90231. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  90232. node.babylonAnimationTargets.push(babylonBone);
  90233. return babylonBone;
  90234. };
  90235. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  90236. var babylonBones = {};
  90237. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  90238. var index = _a[_i];
  90239. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  90240. if (!node) {
  90241. throw new Error(context + ": Failed to find joint " + index);
  90242. }
  90243. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  90244. }
  90245. };
  90246. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  90247. var babylonBone = babylonBones[node.index];
  90248. if (babylonBone) {
  90249. return babylonBone;
  90250. }
  90251. var boneIndex = skin.joints.indexOf(node.index);
  90252. var baseMatrix = BABYLON.Matrix.Identity();
  90253. if (inverseBindMatrixData && boneIndex !== -1) {
  90254. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  90255. baseMatrix.invertToRef(baseMatrix);
  90256. }
  90257. var babylonParentBone = null;
  90258. if (node.parent !== this._rootNode) {
  90259. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  90260. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  90261. }
  90262. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  90263. babylonBones[node.index] = babylonBone;
  90264. return babylonBone;
  90265. };
  90266. GLTFLoader.prototype._getNodeMatrix = function (node) {
  90267. return node.matrix ?
  90268. BABYLON.Matrix.FromArray(node.matrix) :
  90269. 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());
  90270. };
  90271. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  90272. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  90273. var index = indices_1[_i];
  90274. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  90275. if (!node) {
  90276. throw new Error(context + ": Failed to find node " + index);
  90277. }
  90278. this._traverseNode(context, node, action, parentNode);
  90279. }
  90280. };
  90281. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  90282. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  90283. return;
  90284. }
  90285. if (!action(node, parentNode)) {
  90286. return;
  90287. }
  90288. if (node.children) {
  90289. this._traverseNodes(context, node.children, action, node);
  90290. }
  90291. };
  90292. GLTFLoader.prototype._loadAnimations = function () {
  90293. var animations = this._gltf.animations;
  90294. if (!animations) {
  90295. return;
  90296. }
  90297. for (var index = 0; index < animations.length; index++) {
  90298. var animation = animations[index];
  90299. this._loadAnimation("#/animations/" + index, animation);
  90300. }
  90301. };
  90302. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  90303. animation.babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation.index, this._babylonScene);
  90304. for (var index = 0; index < animation.channels.length; index++) {
  90305. var channel = GLTFLoader._GetProperty(animation.channels, index);
  90306. if (!channel) {
  90307. throw new Error(context + ": Failed to find channel " + index);
  90308. }
  90309. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  90310. if (!sampler) {
  90311. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  90312. }
  90313. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  90314. }
  90315. };
  90316. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  90317. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  90318. if (!targetNode) {
  90319. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  90320. }
  90321. var targetPath;
  90322. var animationType;
  90323. switch (channel.target.path) {
  90324. case "translation": {
  90325. targetPath = "position";
  90326. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  90327. break;
  90328. }
  90329. case "rotation": {
  90330. targetPath = "rotationQuaternion";
  90331. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  90332. break;
  90333. }
  90334. case "scale": {
  90335. targetPath = "scaling";
  90336. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  90337. break;
  90338. }
  90339. case "weights": {
  90340. targetPath = "influence";
  90341. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  90342. break;
  90343. }
  90344. default: {
  90345. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  90346. }
  90347. }
  90348. var inputData;
  90349. var outputData;
  90350. var checkSuccess = function () {
  90351. if (!inputData || !outputData) {
  90352. return;
  90353. }
  90354. var outputBufferOffset = 0;
  90355. var getNextOutputValue;
  90356. switch (targetPath) {
  90357. case "position": {
  90358. getNextOutputValue = function () {
  90359. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  90360. outputBufferOffset += 3;
  90361. return value;
  90362. };
  90363. break;
  90364. }
  90365. case "rotationQuaternion": {
  90366. getNextOutputValue = function () {
  90367. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  90368. outputBufferOffset += 4;
  90369. return value;
  90370. };
  90371. break;
  90372. }
  90373. case "scaling": {
  90374. getNextOutputValue = function () {
  90375. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  90376. outputBufferOffset += 3;
  90377. return value;
  90378. };
  90379. break;
  90380. }
  90381. case "influence": {
  90382. getNextOutputValue = function () {
  90383. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  90384. var value = new Array(numTargets);
  90385. for (var i = 0; i < numTargets; i++) {
  90386. value[i] = outputData[outputBufferOffset++];
  90387. }
  90388. return value;
  90389. };
  90390. break;
  90391. }
  90392. }
  90393. sampler.interpolation = sampler.interpolation || "LINEAR";
  90394. var getNextKey;
  90395. switch (sampler.interpolation) {
  90396. case "STEP": {
  90397. getNextKey = function (frameIndex) { return ({
  90398. frame: inputData[frameIndex],
  90399. value: getNextOutputValue(),
  90400. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  90401. }); };
  90402. break;
  90403. }
  90404. case "LINEAR": {
  90405. getNextKey = function (frameIndex) { return ({
  90406. frame: inputData[frameIndex],
  90407. value: getNextOutputValue()
  90408. }); };
  90409. break;
  90410. }
  90411. case "CUBICSPLINE": {
  90412. getNextKey = function (frameIndex) { return ({
  90413. frame: inputData[frameIndex],
  90414. inTangent: getNextOutputValue(),
  90415. value: getNextOutputValue(),
  90416. outTangent: getNextOutputValue()
  90417. }); };
  90418. break;
  90419. }
  90420. default: {
  90421. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  90422. }
  90423. }
  90424. ;
  90425. var keys;
  90426. if (inputData.length === 1) {
  90427. var key = getNextKey(0);
  90428. keys = [
  90429. { frame: key.frame, value: key.value },
  90430. { frame: key.frame + 1, value: key.value }
  90431. ];
  90432. }
  90433. else {
  90434. keys = new Array(inputData.length);
  90435. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  90436. keys[frameIndex] = getNextKey(frameIndex);
  90437. }
  90438. }
  90439. if (targetPath === "influence") {
  90440. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  90441. var _loop_7 = function (targetIndex) {
  90442. var morphTarget = morphTargetManager.getTarget(targetIndex);
  90443. var animationName = animation.babylonAnimationGroup.name + "_channel" + animation.babylonAnimationGroup.targetedAnimations.length;
  90444. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  90445. babylonAnimation.setKeys(keys.map(function (key) { return ({
  90446. frame: key.frame,
  90447. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  90448. value: key.value[targetIndex],
  90449. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  90450. }); }));
  90451. animation.babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  90452. };
  90453. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  90454. _loop_7(targetIndex);
  90455. }
  90456. }
  90457. else {
  90458. var animationName = animation.babylonAnimationGroup.name + "_channel" + animation.babylonAnimationGroup.targetedAnimations.length;
  90459. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  90460. babylonAnimation.setKeys(keys);
  90461. if (targetNode.babylonAnimationTargets) {
  90462. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  90463. var target = _a[_i];
  90464. animation.babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  90465. }
  90466. }
  90467. }
  90468. };
  90469. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  90470. if (!inputAccessor) {
  90471. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  90472. }
  90473. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  90474. inputData = data;
  90475. checkSuccess();
  90476. });
  90477. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  90478. if (!outputAccessor) {
  90479. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  90480. }
  90481. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  90482. outputData = data;
  90483. checkSuccess();
  90484. });
  90485. };
  90486. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  90487. var _this = this;
  90488. this._addPendingData(buffer);
  90489. if (buffer.loadedData) {
  90490. onSuccess(buffer.loadedData);
  90491. this._removePendingData(buffer);
  90492. }
  90493. else if (buffer.loadedObservable) {
  90494. buffer.loadedObservable.add(function (buffer) {
  90495. onSuccess(buffer.loadedData);
  90496. _this._removePendingData(buffer);
  90497. });
  90498. }
  90499. else {
  90500. if (!buffer.uri) {
  90501. throw new Error(context + ": Uri is missing");
  90502. }
  90503. buffer.loadedObservable = new BABYLON.Observable();
  90504. buffer.loadedObservable.add(function (buffer) {
  90505. onSuccess(buffer.loadedData);
  90506. _this._removePendingData(buffer);
  90507. });
  90508. this._loadUriAsync(context, buffer.uri, function (data) {
  90509. buffer.loadedData = data;
  90510. buffer.loadedObservable.notifyObservers(buffer);
  90511. buffer.loadedObservable = undefined;
  90512. });
  90513. }
  90514. };
  90515. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  90516. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  90517. if (!buffer) {
  90518. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  90519. }
  90520. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  90521. var data;
  90522. try {
  90523. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  90524. }
  90525. catch (e) {
  90526. throw new Error(context + ": " + e.message);
  90527. }
  90528. onSuccess(data);
  90529. });
  90530. };
  90531. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  90532. var _this = this;
  90533. if (accessor.sparse) {
  90534. throw new Error(context + ": Sparse accessors are not currently supported");
  90535. }
  90536. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  90537. if (!bufferView) {
  90538. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  90539. }
  90540. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  90541. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  90542. var data;
  90543. var byteOffset = accessor.byteOffset || 0;
  90544. var byteStride = bufferView.byteStride;
  90545. if (byteStride === 0) {
  90546. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  90547. }
  90548. try {
  90549. switch (accessor.componentType) {
  90550. case GLTF2.EComponentType.BYTE: {
  90551. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  90552. break;
  90553. }
  90554. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  90555. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  90556. break;
  90557. }
  90558. case GLTF2.EComponentType.SHORT: {
  90559. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  90560. break;
  90561. }
  90562. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  90563. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  90564. break;
  90565. }
  90566. case GLTF2.EComponentType.UNSIGNED_INT: {
  90567. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  90568. break;
  90569. }
  90570. case GLTF2.EComponentType.FLOAT: {
  90571. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  90572. break;
  90573. }
  90574. default: {
  90575. throw new Error(context + ": Invalid component type " + accessor.componentType);
  90576. }
  90577. }
  90578. }
  90579. catch (e) {
  90580. throw new Error(context + ": " + e);
  90581. }
  90582. onSuccess(data);
  90583. });
  90584. };
  90585. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  90586. byteOffset += data.byteOffset;
  90587. var targetLength = count * numComponents;
  90588. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  90589. return new typedArray(data.buffer, byteOffset, targetLength);
  90590. }
  90591. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  90592. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  90593. var targetBuffer = new typedArray(targetLength);
  90594. var sourceIndex = 0;
  90595. var targetIndex = 0;
  90596. while (targetIndex < targetLength) {
  90597. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  90598. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  90599. targetIndex++;
  90600. }
  90601. sourceIndex += elementStride;
  90602. }
  90603. return targetBuffer;
  90604. };
  90605. GLTFLoader.prototype._addPendingData = function (data) {
  90606. if (!this._renderReady) {
  90607. this._renderPendingCount++;
  90608. }
  90609. this._addLoaderPendingData(data);
  90610. };
  90611. GLTFLoader.prototype._removePendingData = function (data) {
  90612. var _this = this;
  90613. if (!this._renderReady) {
  90614. if (--this._renderPendingCount === 0) {
  90615. this._addLoaderPendingData(this);
  90616. this._compileMaterialsAsync(function () {
  90617. _this._compileShadowGeneratorsAsync(function () {
  90618. _this._removeLoaderPendingData(_this);
  90619. _this._renderReady = true;
  90620. _this._onRenderReady();
  90621. });
  90622. });
  90623. }
  90624. }
  90625. this._removeLoaderPendingData(data);
  90626. };
  90627. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  90628. this._loaderPendingCount++;
  90629. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  90630. var tracker = _a[_i];
  90631. tracker._addPendingData(data);
  90632. }
  90633. };
  90634. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  90635. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  90636. var tracker = _a[_i];
  90637. tracker._removePendingData(data);
  90638. }
  90639. if (--this._loaderPendingCount === 0) {
  90640. this._onComplete();
  90641. }
  90642. };
  90643. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  90644. var _this = this;
  90645. var tracker = new GLTFLoaderTracker(function () {
  90646. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  90647. onComplete();
  90648. });
  90649. this._loaderTrackers.push(tracker);
  90650. this._addLoaderPendingData(tracker);
  90651. action();
  90652. this._removeLoaderPendingData(tracker);
  90653. };
  90654. GLTFLoader.prototype._getDefaultMaterial = function () {
  90655. if (!this._defaultMaterial) {
  90656. var id = "__gltf_default";
  90657. var material = this._babylonScene.getMaterialByName(id);
  90658. if (!material) {
  90659. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  90660. material.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  90661. material.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  90662. material.metallic = 1;
  90663. material.roughness = 1;
  90664. }
  90665. this._defaultMaterial = material;
  90666. }
  90667. return this._defaultMaterial;
  90668. };
  90669. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  90670. var babylonMaterial = material.babylonMaterial;
  90671. // Ensure metallic workflow
  90672. babylonMaterial.metallic = 1;
  90673. babylonMaterial.roughness = 1;
  90674. var properties = material.pbrMetallicRoughness;
  90675. if (!properties) {
  90676. return;
  90677. }
  90678. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  90679. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  90680. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  90681. if (properties.baseColorTexture) {
  90682. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  90683. if (!texture) {
  90684. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  90685. }
  90686. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  90687. }
  90688. if (properties.metallicRoughnessTexture) {
  90689. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  90690. if (!texture) {
  90691. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  90692. }
  90693. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  90694. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  90695. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  90696. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  90697. }
  90698. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  90699. };
  90700. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  90701. if (material.babylonMaterial) {
  90702. assign(material.babylonMaterial, false);
  90703. return;
  90704. }
  90705. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  90706. return;
  90707. }
  90708. this._createPbrMaterial(material);
  90709. this._loadMaterialBaseProperties(context, material);
  90710. this._loadMaterialMetallicRoughnessProperties(context, material);
  90711. assign(material.babylonMaterial, true);
  90712. };
  90713. GLTFLoader.prototype._createPbrMaterial = function (material) {
  90714. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  90715. babylonMaterial.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  90716. material.babylonMaterial = babylonMaterial;
  90717. };
  90718. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  90719. var babylonMaterial = material.babylonMaterial;
  90720. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  90721. if (material.doubleSided) {
  90722. babylonMaterial.backFaceCulling = false;
  90723. babylonMaterial.twoSidedLighting = true;
  90724. }
  90725. if (material.normalTexture) {
  90726. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  90727. if (!texture) {
  90728. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  90729. }
  90730. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  90731. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  90732. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  90733. if (material.normalTexture.scale != null) {
  90734. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  90735. }
  90736. }
  90737. if (material.occlusionTexture) {
  90738. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  90739. if (!texture) {
  90740. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  90741. }
  90742. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  90743. babylonMaterial.useAmbientInGrayScale = true;
  90744. if (material.occlusionTexture.strength != null) {
  90745. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  90746. }
  90747. }
  90748. if (material.emissiveTexture) {
  90749. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  90750. if (!texture) {
  90751. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  90752. }
  90753. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  90754. }
  90755. };
  90756. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  90757. var babylonMaterial = material.babylonMaterial;
  90758. var alphaMode = material.alphaMode || "OPAQUE";
  90759. switch (alphaMode) {
  90760. case "OPAQUE": {
  90761. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  90762. break;
  90763. }
  90764. case "MASK": {
  90765. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  90766. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  90767. if (colorFactor) {
  90768. if (colorFactor[3] == 0) {
  90769. babylonMaterial.alphaCutOff = 1;
  90770. }
  90771. else {
  90772. babylonMaterial.alphaCutOff /= colorFactor[3];
  90773. }
  90774. }
  90775. if (babylonMaterial.albedoTexture) {
  90776. babylonMaterial.albedoTexture.hasAlpha = true;
  90777. }
  90778. break;
  90779. }
  90780. case "BLEND": {
  90781. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  90782. if (colorFactor) {
  90783. babylonMaterial.alpha = colorFactor[3];
  90784. }
  90785. if (babylonMaterial.albedoTexture) {
  90786. babylonMaterial.albedoTexture.hasAlpha = true;
  90787. babylonMaterial.useAlphaFromAlbedoTexture = true;
  90788. }
  90789. break;
  90790. }
  90791. default: {
  90792. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  90793. }
  90794. }
  90795. };
  90796. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  90797. var _this = this;
  90798. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  90799. if (!sampler) {
  90800. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  90801. }
  90802. this._loadSampler("#/samplers/" + sampler.index, sampler);
  90803. this._addPendingData(texture);
  90804. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, sampler.noMipMaps, false, sampler.samplingMode, function () {
  90805. _this._tryCatchOnError(function () {
  90806. _this._removePendingData(texture);
  90807. });
  90808. }, function (message) {
  90809. _this._tryCatchOnError(function () {
  90810. throw new Error(context + ": " + message);
  90811. });
  90812. });
  90813. if (texture.url) {
  90814. babylonTexture.updateURL(texture.url);
  90815. }
  90816. else if (texture.dataReadyObservable) {
  90817. texture.dataReadyObservable.add(function (texture) {
  90818. babylonTexture.updateURL(texture.url);
  90819. });
  90820. }
  90821. else {
  90822. texture.dataReadyObservable = new BABYLON.Observable();
  90823. texture.dataReadyObservable.add(function (texture) {
  90824. babylonTexture.updateURL(texture.url);
  90825. });
  90826. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  90827. if (!image_1) {
  90828. throw new Error(context + ": Failed to find source " + texture.source);
  90829. }
  90830. this._loadImageAsync("#/images/" + image_1.index, image_1, function (data) {
  90831. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  90832. texture.dataReadyObservable.notifyObservers(texture);
  90833. texture.dataReadyObservable = undefined;
  90834. });
  90835. }
  90836. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  90837. babylonTexture.wrapU = sampler.wrapU;
  90838. babylonTexture.wrapV = sampler.wrapV;
  90839. babylonTexture.name = texture.name || "texture" + texture.index;
  90840. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  90841. return babylonTexture;
  90842. };
  90843. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  90844. if (sampler.noMipMaps != undefined) {
  90845. return;
  90846. }
  90847. sampler.noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  90848. sampler.samplingMode = GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter);
  90849. sampler.wrapU = GLTFLoader._GetTextureWrapMode(context, sampler.wrapS);
  90850. sampler.wrapV = GLTFLoader._GetTextureWrapMode(context, sampler.wrapT);
  90851. };
  90852. GLTFLoader.prototype._loadImageAsync = function (context, image, onSuccess) {
  90853. if (image.uri) {
  90854. this._loadUriAsync(context, image.uri, onSuccess);
  90855. }
  90856. else {
  90857. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  90858. if (!bufferView) {
  90859. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  90860. }
  90861. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  90862. }
  90863. };
  90864. GLTFLoader.prototype._loadUriAsync = function (context, uri, onSuccess) {
  90865. var _this = this;
  90866. if (GLTF2.GLTFUtils.IsBase64(uri)) {
  90867. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(uri)));
  90868. return;
  90869. }
  90870. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  90871. throw new Error(context + ": Uri '" + uri + "' is invalid");
  90872. }
  90873. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  90874. _this._tryCatchOnError(function () {
  90875. onSuccess(new Uint8Array(data));
  90876. });
  90877. }, function (event) {
  90878. _this._tryCatchOnError(function () {
  90879. if (request && !_this._renderReady) {
  90880. request._lengthComputable = event.lengthComputable;
  90881. request._loaded = event.loaded;
  90882. request._total = event.total;
  90883. _this._onProgress();
  90884. }
  90885. });
  90886. }, this._babylonScene.database, true, function (request, exception) {
  90887. _this._tryCatchOnError(function () {
  90888. throw new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request);
  90889. });
  90890. });
  90891. this._requests.push(request);
  90892. };
  90893. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  90894. if (this._disposed) {
  90895. return;
  90896. }
  90897. try {
  90898. handler();
  90899. }
  90900. catch (e) {
  90901. BABYLON.Tools.Error("glTF Loader: " + e.message);
  90902. if (this._errorCallback) {
  90903. this._errorCallback(e.message, e);
  90904. }
  90905. this.dispose();
  90906. }
  90907. };
  90908. GLTFLoader._AssignIndices = function (array) {
  90909. if (array) {
  90910. for (var index = 0; index < array.length; index++) {
  90911. array[index].index = index;
  90912. }
  90913. }
  90914. };
  90915. GLTFLoader._GetProperty = function (array, index) {
  90916. if (!array || index == undefined || !array[index]) {
  90917. return null;
  90918. }
  90919. return array[index];
  90920. };
  90921. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  90922. // Set defaults if undefined
  90923. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  90924. switch (mode) {
  90925. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  90926. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  90927. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  90928. default:
  90929. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  90930. return BABYLON.Texture.WRAP_ADDRESSMODE;
  90931. }
  90932. };
  90933. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  90934. // Set defaults if undefined
  90935. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  90936. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  90937. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  90938. switch (minFilter) {
  90939. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  90940. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  90941. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  90942. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  90943. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  90944. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  90945. default:
  90946. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  90947. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  90948. }
  90949. }
  90950. else {
  90951. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  90952. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  90953. }
  90954. switch (minFilter) {
  90955. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  90956. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  90957. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  90958. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  90959. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  90960. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  90961. default:
  90962. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  90963. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  90964. }
  90965. }
  90966. };
  90967. GLTFLoader._GetNumComponents = function (context, type) {
  90968. switch (type) {
  90969. case "SCALAR": return 1;
  90970. case "VEC2": return 2;
  90971. case "VEC3": return 3;
  90972. case "VEC4": return 4;
  90973. case "MAT2": return 4;
  90974. case "MAT3": return 9;
  90975. case "MAT4": return 16;
  90976. }
  90977. throw new Error(context + ": Invalid type " + type);
  90978. };
  90979. GLTFLoader.prototype._compileMaterialAsync = function (babylonMaterial, babylonMesh, onSuccess) {
  90980. var _this = this;
  90981. if (this.useClipPlane) {
  90982. babylonMaterial.forceCompilation(babylonMesh, function () {
  90983. babylonMaterial.forceCompilation(babylonMesh, function () {
  90984. _this._tryCatchOnError(onSuccess);
  90985. }, { clipPlane: true });
  90986. });
  90987. }
  90988. else {
  90989. babylonMaterial.forceCompilation(babylonMesh, function () {
  90990. _this._tryCatchOnError(onSuccess);
  90991. });
  90992. }
  90993. };
  90994. GLTFLoader.prototype._compileMaterialsAsync = function (onSuccess) {
  90995. if (!this.compileMaterials || !this._gltf.materials) {
  90996. onSuccess();
  90997. return;
  90998. }
  90999. var meshes = this._getMeshes();
  91000. var remaining = 0;
  91001. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  91002. var mesh = meshes_1[_i];
  91003. if (mesh.material instanceof BABYLON.MultiMaterial) {
  91004. for (var _a = 0, _b = mesh.material.subMaterials; _a < _b.length; _a++) {
  91005. var subMaterial = _b[_a];
  91006. if (subMaterial) {
  91007. remaining++;
  91008. }
  91009. }
  91010. }
  91011. else if (mesh.material) {
  91012. remaining++;
  91013. }
  91014. }
  91015. if (remaining === 0) {
  91016. onSuccess();
  91017. return;
  91018. }
  91019. for (var _c = 0, meshes_2 = meshes; _c < meshes_2.length; _c++) {
  91020. var mesh = meshes_2[_c];
  91021. if (mesh.material instanceof BABYLON.MultiMaterial) {
  91022. for (var _d = 0, _e = mesh.material.subMaterials; _d < _e.length; _d++) {
  91023. var subMaterial = _e[_d];
  91024. if (subMaterial) {
  91025. this._compileMaterialAsync(subMaterial, mesh, function () {
  91026. if (--remaining === 0) {
  91027. onSuccess();
  91028. }
  91029. });
  91030. }
  91031. }
  91032. }
  91033. else if (mesh.material) {
  91034. this._compileMaterialAsync(mesh.material, mesh, function () {
  91035. if (--remaining === 0) {
  91036. onSuccess();
  91037. }
  91038. });
  91039. }
  91040. }
  91041. };
  91042. GLTFLoader.prototype._compileShadowGeneratorsAsync = function (onSuccess) {
  91043. var _this = this;
  91044. if (!this.compileShadowGenerators) {
  91045. onSuccess();
  91046. return;
  91047. }
  91048. var lights = this._babylonScene.lights;
  91049. var remaining = 0;
  91050. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  91051. var light = lights_1[_i];
  91052. var generator = light.getShadowGenerator();
  91053. if (generator) {
  91054. remaining++;
  91055. }
  91056. }
  91057. if (remaining === 0) {
  91058. onSuccess();
  91059. return;
  91060. }
  91061. for (var _a = 0, lights_2 = lights; _a < lights_2.length; _a++) {
  91062. var light = lights_2[_a];
  91063. var generator = light.getShadowGenerator();
  91064. if (generator) {
  91065. generator.forceCompilation(function () {
  91066. if (--remaining === 0) {
  91067. _this._tryCatchOnError(onSuccess);
  91068. }
  91069. });
  91070. }
  91071. }
  91072. };
  91073. GLTFLoader.prototype._abortRequests = function () {
  91074. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  91075. var request = _a[_i];
  91076. request.abort();
  91077. }
  91078. this._requests.length = 0;
  91079. };
  91080. GLTFLoader.prototype._releaseResources = function () {
  91081. if (this._gltf.textures) {
  91082. for (var _i = 0, _a = this._gltf.textures; _i < _a.length; _i++) {
  91083. var texture = _a[_i];
  91084. if (texture.url) {
  91085. URL.revokeObjectURL(texture.url);
  91086. texture.url = undefined;
  91087. }
  91088. }
  91089. }
  91090. };
  91091. GLTFLoader.Extensions = {};
  91092. return GLTFLoader;
  91093. }());
  91094. GLTF2.GLTFLoader = GLTFLoader;
  91095. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  91096. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  91097. })(BABYLON || (BABYLON = {}));
  91098. //# sourceMappingURL=babylon.glTFLoader.js.map
  91099. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91100. var BABYLON;
  91101. (function (BABYLON) {
  91102. var GLTF2;
  91103. (function (GLTF2) {
  91104. /**
  91105. * Utils functions for GLTF
  91106. */
  91107. var GLTFUtils = /** @class */ (function () {
  91108. function GLTFUtils() {
  91109. }
  91110. /**
  91111. * If the uri is a base64 string
  91112. * @param uri: the uri to test
  91113. */
  91114. GLTFUtils.IsBase64 = function (uri) {
  91115. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  91116. };
  91117. /**
  91118. * Decode the base64 uri
  91119. * @param uri: the uri to decode
  91120. */
  91121. GLTFUtils.DecodeBase64 = function (uri) {
  91122. var decodedString = atob(uri.split(",")[1]);
  91123. var bufferLength = decodedString.length;
  91124. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  91125. for (var i = 0; i < bufferLength; i++) {
  91126. bufferView[i] = decodedString.charCodeAt(i);
  91127. }
  91128. return bufferView.buffer;
  91129. };
  91130. GLTFUtils.ValidateUri = function (uri) {
  91131. return (uri.indexOf("..") === -1);
  91132. };
  91133. return GLTFUtils;
  91134. }());
  91135. GLTF2.GLTFUtils = GLTFUtils;
  91136. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  91137. })(BABYLON || (BABYLON = {}));
  91138. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  91139. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91140. var BABYLON;
  91141. (function (BABYLON) {
  91142. var GLTF2;
  91143. (function (GLTF2) {
  91144. var GLTFLoaderExtension = /** @class */ (function () {
  91145. function GLTFLoaderExtension() {
  91146. this.enabled = true;
  91147. }
  91148. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  91149. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  91150. GLTFLoaderExtension.prototype._loadRoot = function (loader, context, root) { return false; };
  91151. GLTFLoaderExtension.prototype._loadScene = function (loader, context, scene) { return false; };
  91152. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  91153. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  91154. var _this = this;
  91155. if (!property.extensions) {
  91156. return false;
  91157. }
  91158. var extension = property.extensions[this.name];
  91159. if (!extension) {
  91160. return false;
  91161. }
  91162. // Clear out the extension before executing the action to avoid recursing into the same property.
  91163. property.extensions[this.name] = undefined;
  91164. action(context + "extensions/" + this.name, extension, function () {
  91165. // Restore the extension after completing the action.
  91166. property.extensions[_this.name] = extension;
  91167. });
  91168. return true;
  91169. };
  91170. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  91171. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  91172. };
  91173. GLTFLoaderExtension.LoadRoot = function (loader, context, root) {
  91174. return this._ApplyExtensions(function (extension) { return extension._loadRoot(loader, context, root); });
  91175. };
  91176. GLTFLoaderExtension.LoadScene = function (loader, context, scene) {
  91177. return this._ApplyExtensions(function (extension) { return extension._loadScene(loader, context, scene); });
  91178. };
  91179. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  91180. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  91181. };
  91182. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  91183. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  91184. };
  91185. GLTFLoaderExtension._ApplyExtensions = function (action) {
  91186. var extensions = GLTFLoaderExtension._Extensions;
  91187. if (!extensions) {
  91188. return false;
  91189. }
  91190. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  91191. var extension = extensions_1[_i];
  91192. if (extension.enabled && action(extension)) {
  91193. return true;
  91194. }
  91195. }
  91196. return false;
  91197. };
  91198. //
  91199. // Utilities
  91200. //
  91201. GLTFLoaderExtension._Extensions = [];
  91202. return GLTFLoaderExtension;
  91203. }());
  91204. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  91205. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  91206. })(BABYLON || (BABYLON = {}));
  91207. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  91208. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  91209. var BABYLON;
  91210. (function (BABYLON) {
  91211. var GLTF2;
  91212. (function (GLTF2) {
  91213. var Extensions;
  91214. (function (Extensions) {
  91215. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  91216. var MSFTLOD = /** @class */ (function (_super) {
  91217. __extends(MSFTLOD, _super);
  91218. function MSFTLOD() {
  91219. var _this = _super !== null && _super.apply(this, arguments) || this;
  91220. /**
  91221. * Specify the minimal delay between LODs in ms (default = 250)
  91222. */
  91223. _this.Delay = 250;
  91224. return _this;
  91225. }
  91226. Object.defineProperty(MSFTLOD.prototype, "name", {
  91227. get: function () {
  91228. return "MSFT_lod";
  91229. },
  91230. enumerable: true,
  91231. configurable: true
  91232. });
  91233. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  91234. return this._loadExtension(context, node, function (context, extension, onComplete) {
  91235. for (var i = extension.ids.length - 1; i >= 0; i--) {
  91236. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  91237. if (!lodNode) {
  91238. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  91239. }
  91240. loader._traverseNode(context, lodNode, action, parentNode);
  91241. }
  91242. loader._traverseNode(context, node, action, parentNode);
  91243. onComplete();
  91244. });
  91245. };
  91246. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  91247. var _this = this;
  91248. return this._loadExtension(context, node, function (context, extension, onComplete) {
  91249. var nodes = [node];
  91250. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  91251. var index = _a[_i];
  91252. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  91253. if (!lodNode) {
  91254. throw new Error(context + ": Failed to find node " + index);
  91255. }
  91256. nodes.push(lodNode);
  91257. }
  91258. loader._addLoaderPendingData(node);
  91259. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  91260. loader._removeLoaderPendingData(node);
  91261. onComplete();
  91262. });
  91263. });
  91264. };
  91265. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  91266. var _this = this;
  91267. loader._whenAction(function () {
  91268. loader._loadNode(context, nodes[index]);
  91269. }, function () {
  91270. if (index !== nodes.length - 1) {
  91271. var previousNode = nodes[index + 1];
  91272. previousNode.babylonMesh.setEnabled(false);
  91273. }
  91274. if (index === 0) {
  91275. onComplete();
  91276. return;
  91277. }
  91278. setTimeout(function () {
  91279. loader._tryCatchOnError(function () {
  91280. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  91281. });
  91282. }, _this.Delay);
  91283. });
  91284. };
  91285. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  91286. var _this = this;
  91287. return this._loadExtension(context, material, function (context, extension, onComplete) {
  91288. var materials = [material];
  91289. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  91290. var index = _a[_i];
  91291. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  91292. if (!lodMaterial) {
  91293. throw new Error(context + ": Failed to find material " + index);
  91294. }
  91295. materials.push(lodMaterial);
  91296. }
  91297. loader._addLoaderPendingData(material);
  91298. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  91299. loader._removeLoaderPendingData(material);
  91300. onComplete();
  91301. });
  91302. });
  91303. };
  91304. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  91305. var _this = this;
  91306. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  91307. if (index === materials.length - 1) {
  91308. assign(babylonMaterial, isNew);
  91309. // Load the next LOD when the loader is ready to render.
  91310. loader._executeWhenRenderReady(function () {
  91311. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  91312. });
  91313. }
  91314. else {
  91315. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  91316. assign(babylonMaterial, isNew);
  91317. if (index === 0) {
  91318. onComplete();
  91319. }
  91320. else {
  91321. setTimeout(function () {
  91322. loader._tryCatchOnError(function () {
  91323. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  91324. });
  91325. }, _this.Delay);
  91326. }
  91327. });
  91328. }
  91329. });
  91330. };
  91331. return MSFTLOD;
  91332. }(GLTF2.GLTFLoaderExtension));
  91333. Extensions.MSFTLOD = MSFTLOD;
  91334. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  91335. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  91336. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  91337. })(BABYLON || (BABYLON = {}));
  91338. //# sourceMappingURL=MSFT_lod.js.map
  91339. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  91340. var BABYLON;
  91341. (function (BABYLON) {
  91342. var GLTF2;
  91343. (function (GLTF2) {
  91344. var Extensions;
  91345. (function (Extensions) {
  91346. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  91347. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  91348. function KHRMaterialsPbrSpecularGlossiness() {
  91349. return _super !== null && _super.apply(this, arguments) || this;
  91350. }
  91351. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  91352. get: function () {
  91353. return "KHR_materials_pbrSpecularGlossiness";
  91354. },
  91355. enumerable: true,
  91356. configurable: true
  91357. });
  91358. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  91359. var _this = this;
  91360. return this._loadExtension(context, material, function (context, extension, onComplete) {
  91361. loader._createPbrMaterial(material);
  91362. loader._loadMaterialBaseProperties(context, material);
  91363. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  91364. assign(material.babylonMaterial, true);
  91365. onComplete();
  91366. });
  91367. };
  91368. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  91369. var babylonMaterial = material.babylonMaterial;
  91370. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  91371. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  91372. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  91373. if (properties.diffuseTexture) {
  91374. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  91375. if (!texture) {
  91376. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  91377. }
  91378. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  91379. }
  91380. if (properties.specularGlossinessTexture) {
  91381. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  91382. if (!texture) {
  91383. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  91384. }
  91385. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  91386. babylonMaterial.reflectivityTexture.hasAlpha = true;
  91387. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  91388. }
  91389. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  91390. };
  91391. return KHRMaterialsPbrSpecularGlossiness;
  91392. }(GLTF2.GLTFLoaderExtension));
  91393. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  91394. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  91395. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  91396. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  91397. })(BABYLON || (BABYLON = {}));
  91398. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  91399. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  91400. var BABYLON;
  91401. (function (BABYLON) {
  91402. var GLTF2;
  91403. (function (GLTF2) {
  91404. var Extensions;
  91405. (function (Extensions) {
  91406. var KHRLights = /** @class */ (function (_super) {
  91407. __extends(KHRLights, _super);
  91408. function KHRLights() {
  91409. return _super !== null && _super.apply(this, arguments) || this;
  91410. }
  91411. Object.defineProperty(KHRLights.prototype, "name", {
  91412. get: function () {
  91413. return "KHR_lights";
  91414. },
  91415. enumerable: true,
  91416. configurable: true
  91417. });
  91418. KHRLights.prototype.applyCommonProperties = function (light, lightInfo) {
  91419. if (lightInfo.color) {
  91420. light.diffuse.copyFromFloats(lightInfo.color[0], lightInfo.color[1], lightInfo.color[2]);
  91421. }
  91422. else {
  91423. light.diffuse.copyFromFloats(1, 1, 1);
  91424. }
  91425. if (lightInfo.intensity !== undefined) {
  91426. light.intensity = lightInfo.intensity;
  91427. }
  91428. else {
  91429. light.intensity = 1;
  91430. }
  91431. };
  91432. KHRLights.prototype._loadScene = function (loader, context, scene) {
  91433. return this._loadExtension(context, scene, function (context, extension, onComplete) {
  91434. if (extension.light >= 0 && loader._gltf.extensions) {
  91435. var lightInfo = loader._gltf.extensions.KHR_lights.lights[extension.light];
  91436. if (lightInfo.type !== 'ambient') {
  91437. return;
  91438. }
  91439. var lightColor = lightInfo.color ? lightInfo.color : [1, 1, 1];
  91440. loader._babylonScene.ambientColor.copyFromFloats(lightColor[0], lightColor[1], lightColor[2]);
  91441. }
  91442. onComplete();
  91443. });
  91444. };
  91445. KHRLights.prototype._loadNode = function (loader, context, node) {
  91446. var _this = this;
  91447. return this._loadExtension(context, node, function (context, extension, onComplete) {
  91448. if (extension.light >= 0 && loader._gltf.extensions) {
  91449. var lightInfo = loader._gltf.extensions.KHR_lights.lights[extension.light];
  91450. var name_1 = node.name || 'Light';
  91451. var matrix = void 0;
  91452. if (node.matrix) {
  91453. matrix = BABYLON.Matrix.FromArray(node.matrix);
  91454. }
  91455. else {
  91456. matrix = BABYLON.Matrix.Identity();
  91457. }
  91458. var direction = new BABYLON.Vector3(0, 0, 1);
  91459. if (lightInfo.type == 'directional' || lightInfo.type == 'spot') {
  91460. var rotationMatrix = matrix.getRotationMatrix();
  91461. BABYLON.Vector3.TransformCoordinatesToRef(direction, rotationMatrix, direction);
  91462. }
  91463. var light = void 0;
  91464. if (lightInfo.type == 'directional') {
  91465. light = new BABYLON.DirectionalLight(name_1, direction, loader._babylonScene);
  91466. }
  91467. else {
  91468. var position = matrix.getTranslation();
  91469. if (lightInfo.type == 'spot') {
  91470. var angle = lightInfo.spot && lightInfo.spot.outerConeAngle ? lightInfo.spot.outerConeAngle : Math.PI / 2;
  91471. light = new BABYLON.SpotLight(name_1, position, direction, angle, 2, loader._babylonScene);
  91472. }
  91473. else {
  91474. light = new BABYLON.PointLight(name_1, position, loader._babylonScene);
  91475. }
  91476. }
  91477. _this.applyCommonProperties(light, lightInfo);
  91478. extension.babylonLight = light;
  91479. extension.babylonLight.parent = node.parent ? node.parent.babylonMesh : null;
  91480. if (node.children) {
  91481. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  91482. var index = _a[_i];
  91483. var childNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  91484. if (!childNode) {
  91485. throw new Error(context + ": Failed to find child node " + index);
  91486. }
  91487. loader._loadNode("#/nodes/" + index, childNode);
  91488. }
  91489. }
  91490. }
  91491. onComplete();
  91492. });
  91493. };
  91494. KHRLights.prototype._loadRoot = function (loader, context, root) {
  91495. return this._loadExtension(context, root, function (context, extension, onComplete) {
  91496. extension.lights.forEach(function (light, idx) {
  91497. light.index = idx;
  91498. });
  91499. onComplete();
  91500. });
  91501. };
  91502. return KHRLights;
  91503. }(GLTF2.GLTFLoaderExtension));
  91504. Extensions.KHRLights = KHRLights;
  91505. GLTF2.GLTFLoader.RegisterExtension(new KHRLights());
  91506. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  91507. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  91508. })(BABYLON || (BABYLON = {}));
  91509. //# sourceMappingURL=KHR_lights.js.map
  91510. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  91511. globalObject["BABYLON"] = BABYLON;
  91512. var EffectFallbacks = BABYLON.EffectFallbacks;var EffectCreationOptions = BABYLON.EffectCreationOptions;var Effect = BABYLON.Effect;var KeyboardEventTypes = BABYLON.KeyboardEventTypes;var KeyboardInfo = BABYLON.KeyboardInfo;var KeyboardInfoPre = BABYLON.KeyboardInfoPre;var PointerEventTypes = BABYLON.PointerEventTypes;var PointerInfoBase = BABYLON.PointerInfoBase;var PointerInfoPre = BABYLON.PointerInfoPre;var PointerInfo = BABYLON.PointerInfo;var Color3 = BABYLON.Color3;var Color4 = BABYLON.Color4;var Vector2 = BABYLON.Vector2;var Vector3 = BABYLON.Vector3;var Vector4 = BABYLON.Vector4;var Size = BABYLON.Size;var Quaternion = BABYLON.Quaternion;var Matrix = BABYLON.Matrix;var Plane = BABYLON.Plane;var Viewport = BABYLON.Viewport;var Frustum = BABYLON.Frustum;var Axis = BABYLON.Axis;var BezierCurve = BABYLON.BezierCurve;var Angle = BABYLON.Angle;var Arc2 = BABYLON.Arc2;var Path2 = BABYLON.Path2;var Path3D = BABYLON.Path3D;var Curve3 = BABYLON.Curve3;var PositionNormalVertex = BABYLON.PositionNormalVertex;var PositionNormalTextureVertex = BABYLON.PositionNormalTextureVertex;var Tmp = BABYLON.Tmp;var Scalar = BABYLON.Scalar;var expandToProperty = BABYLON.expandToProperty;var serialize = BABYLON.serialize;var serializeAsTexture = BABYLON.serializeAsTexture;var serializeAsColor3 = BABYLON.serializeAsColor3;var serializeAsFresnelParameters = BABYLON.serializeAsFresnelParameters;var serializeAsVector2 = BABYLON.serializeAsVector2;var serializeAsVector3 = BABYLON.serializeAsVector3;var serializeAsMeshReference = BABYLON.serializeAsMeshReference;var serializeAsColorCurves = BABYLON.serializeAsColorCurves;var serializeAsColor4 = BABYLON.serializeAsColor4;var serializeAsImageProcessingConfiguration = BABYLON.serializeAsImageProcessingConfiguration;var serializeAsQuaternion = BABYLON.serializeAsQuaternion;var SerializationHelper = BABYLON.SerializationHelper;var EventState = BABYLON.EventState;var Observer = BABYLON.Observer;var MultiObserver = BABYLON.MultiObserver;var Observable = BABYLON.Observable;var SmartArray = BABYLON.SmartArray;var SmartArrayNoDuplicate = BABYLON.SmartArrayNoDuplicate;var LoadFileError = BABYLON.LoadFileError;var RetryStrategy = BABYLON.RetryStrategy;var Tools = BABYLON.Tools;var PerfCounter = BABYLON.PerfCounter;var className = BABYLON.className;var AsyncLoop = BABYLON.AsyncLoop;var PromisePolyfill = BABYLON.PromisePolyfill;var _AlphaState = BABYLON._AlphaState;var _DepthCullingState = BABYLON._DepthCullingState;var _StencilState = BABYLON._StencilState;var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;var EngineCapabilities = BABYLON.EngineCapabilities;var Engine = BABYLON.Engine;var Node = BABYLON.Node;var BoundingSphere = BABYLON.BoundingSphere;var BoundingBox = BABYLON.BoundingBox;var BoundingInfo = BABYLON.BoundingInfo;var TransformNode = BABYLON.TransformNode;var AbstractMesh = BABYLON.AbstractMesh;var Light = BABYLON.Light;var Camera = BABYLON.Camera;var RenderingManager = BABYLON.RenderingManager;var RenderingGroup = BABYLON.RenderingGroup;var RenderingGroupInfo = BABYLON.RenderingGroupInfo;var Scene = BABYLON.Scene;var KeepAssets = BABYLON.KeepAssets;var AssetContainer = BABYLON.AssetContainer;var Buffer = BABYLON.Buffer;var VertexBuffer = BABYLON.VertexBuffer;var DummyInternalTextureTracker = BABYLON.DummyInternalTextureTracker;var InternalTexture = BABYLON.InternalTexture;var BaseTexture = BABYLON.BaseTexture;var Texture = BABYLON.Texture;var _InstancesBatch = BABYLON._InstancesBatch;var Mesh = BABYLON.Mesh;var BaseSubMesh = BABYLON.BaseSubMesh;var SubMesh = BABYLON.SubMesh;var MaterialDefines = BABYLON.MaterialDefines;var Material = BABYLON.Material;var UniformBuffer = BABYLON.UniformBuffer;var VertexData = BABYLON.VertexData;var Geometry = BABYLON.Geometry;var _PrimitiveGeometry = BABYLON._PrimitiveGeometry;var RibbonGeometry = BABYLON.RibbonGeometry;var BoxGeometry = BABYLON.BoxGeometry;var SphereGeometry = BABYLON.SphereGeometry;var DiscGeometry = BABYLON.DiscGeometry;var CylinderGeometry = BABYLON.CylinderGeometry;var TorusGeometry = BABYLON.TorusGeometry;var GroundGeometry = BABYLON.GroundGeometry;var TiledGroundGeometry = BABYLON.TiledGroundGeometry;var PlaneGeometry = BABYLON.PlaneGeometry;var TorusKnotGeometry = BABYLON.TorusKnotGeometry;var PostProcessManager = BABYLON.PostProcessManager;var PerformanceMonitor = BABYLON.PerformanceMonitor;var RollingAverage = BABYLON.RollingAverage;var ImageProcessingConfiguration = BABYLON.ImageProcessingConfiguration;var ColorGradingTexture = BABYLON.ColorGradingTexture;var ColorCurves = BABYLON.ColorCurves;var MaterialHelper = BABYLON.MaterialHelper;var PushMaterial = BABYLON.PushMaterial;var StandardMaterialDefines = BABYLON.StandardMaterialDefines;var StandardMaterial = BABYLON.StandardMaterial;var PBRBaseMaterial = BABYLON.PBRBaseMaterial;var PBRBaseSimpleMaterial = BABYLON.PBRBaseSimpleMaterial;var PBRMaterial = BABYLON.PBRMaterial;var PBRMetallicRoughnessMaterial = BABYLON.PBRMetallicRoughnessMaterial;var PBRSpecularGlossinessMaterial = BABYLON.PBRSpecularGlossinessMaterial;var CameraInputsManager = BABYLON.CameraInputsManager;var TargetCamera = BABYLON.TargetCamera;var FreeCameraMouseInput = BABYLON.FreeCameraMouseInput;var FreeCameraKeyboardMoveInput = BABYLON.FreeCameraKeyboardMoveInput;var FreeCameraInputsManager = BABYLON.FreeCameraInputsManager;var FreeCamera = BABYLON.FreeCamera;var ArcRotateCameraKeyboardMoveInput = BABYLON.ArcRotateCameraKeyboardMoveInput;var ArcRotateCameraMouseWheelInput = BABYLON.ArcRotateCameraMouseWheelInput;var ArcRotateCameraPointersInput = BABYLON.ArcRotateCameraPointersInput;var ArcRotateCameraInputsManager = BABYLON.ArcRotateCameraInputsManager;var ArcRotateCamera = BABYLON.ArcRotateCamera;var HemisphericLight = BABYLON.HemisphericLight;var ShadowLight = BABYLON.ShadowLight;var PointLight = BABYLON.PointLight;var DirectionalLight = BABYLON.DirectionalLight;var SpotLight = BABYLON.SpotLight;var AnimationRange = BABYLON.AnimationRange;var AnimationEvent = BABYLON.AnimationEvent;var PathCursor = BABYLON.PathCursor;var Animation = BABYLON.Animation;var TargetedAnimation = BABYLON.TargetedAnimation;var AnimationGroup = BABYLON.AnimationGroup;var RuntimeAnimation = BABYLON.RuntimeAnimation;var Animatable = BABYLON.Animatable;var EasingFunction = BABYLON.EasingFunction;var CircleEase = BABYLON.CircleEase;var BackEase = BABYLON.BackEase;var BounceEase = BABYLON.BounceEase;var CubicEase = BABYLON.CubicEase;var ElasticEase = BABYLON.ElasticEase;var ExponentialEase = BABYLON.ExponentialEase;var PowerEase = BABYLON.PowerEase;var QuadraticEase = BABYLON.QuadraticEase;var QuarticEase = BABYLON.QuarticEase;var QuinticEase = BABYLON.QuinticEase;var SineEase = BABYLON.SineEase;var BezierCurveEase = BABYLON.BezierCurveEase;var Condition = BABYLON.Condition;var ValueCondition = BABYLON.ValueCondition;var PredicateCondition = BABYLON.PredicateCondition;var StateCondition = BABYLON.StateCondition;var Action = BABYLON.Action;var ActionEvent = BABYLON.ActionEvent;var ActionManager = BABYLON.ActionManager;var InterpolateValueAction = BABYLON.InterpolateValueAction;var SwitchBooleanAction = BABYLON.SwitchBooleanAction;var SetStateAction = BABYLON.SetStateAction;var SetValueAction = BABYLON.SetValueAction;var IncrementValueAction = BABYLON.IncrementValueAction;var PlayAnimationAction = BABYLON.PlayAnimationAction;var StopAnimationAction = BABYLON.StopAnimationAction;var DoNothingAction = BABYLON.DoNothingAction;var CombineAction = BABYLON.CombineAction;var ExecuteCodeAction = BABYLON.ExecuteCodeAction;var SetParentAction = BABYLON.SetParentAction;var PlaySoundAction = BABYLON.PlaySoundAction;var StopSoundAction = BABYLON.StopSoundAction;var SpriteManager = BABYLON.SpriteManager;var Sprite = BABYLON.Sprite;var IntersectionInfo = BABYLON.IntersectionInfo;var PickingInfo = BABYLON.PickingInfo;var Ray = BABYLON.Ray;var Collider = BABYLON.Collider;var CollisionCoordinatorWorker = BABYLON.CollisionCoordinatorWorker;var CollisionCoordinatorLegacy = BABYLON.CollisionCoordinatorLegacy;var Particle = BABYLON.Particle;var ParticleSystem = BABYLON.ParticleSystem;var BoxParticleEmitter = BABYLON.BoxParticleEmitter;var ConeParticleEmitter = BABYLON.ConeParticleEmitter;var SphereParticleEmitter = BABYLON.SphereParticleEmitter;var SphereDirectedParticleEmitter = BABYLON.SphereDirectedParticleEmitter;var SolidParticle = BABYLON.SolidParticle;var ModelShape = BABYLON.ModelShape;var DepthSortedParticle = BABYLON.DepthSortedParticle;var SolidParticleSystem = BABYLON.SolidParticleSystem;var ShaderMaterial = BABYLON.ShaderMaterial;var GroundMesh = BABYLON.GroundMesh;var InstancedMesh = BABYLON.InstancedMesh;var LinesMesh = BABYLON.LinesMesh;var MeshBuilder = BABYLON.MeshBuilder;var AudioEngine = BABYLON.AudioEngine;var Sound = BABYLON.Sound;var SoundTrack = BABYLON.SoundTrack;var Analyser = BABYLON.Analyser;var CubeTexture = BABYLON.CubeTexture;var RenderTargetTexture = BABYLON.RenderTargetTexture;var MultiRenderTarget = BABYLON.MultiRenderTarget;var MirrorTexture = BABYLON.MirrorTexture;var RefractionTexture = BABYLON.RefractionTexture;var DynamicTexture = BABYLON.DynamicTexture;var VideoTexture = BABYLON.VideoTexture;var RawTexture = BABYLON.RawTexture;var PostProcess = BABYLON.PostProcess;var PassPostProcess = BABYLON.PassPostProcess;var ShadowGenerator = BABYLON.ShadowGenerator;var DefaultLoadingScreen = BABYLON.DefaultLoadingScreen;var SceneLoaderProgressEvent = BABYLON.SceneLoaderProgressEvent;var SceneLoader = BABYLON.SceneLoader;var FilesInput = BABYLON.FilesInput;var StringDictionary = BABYLON.StringDictionary;var Tags = BABYLON.Tags;var AndOrNotEvaluator = BABYLON.AndOrNotEvaluator;var Database = BABYLON.Database;var FresnelParameters = BABYLON.FresnelParameters;var MultiMaterial = BABYLON.MultiMaterial;var FreeCameraTouchInput = BABYLON.FreeCameraTouchInput;var TouchCamera = BABYLON.TouchCamera;var ProceduralTexture = BABYLON.ProceduralTexture;var CustomProceduralTexture = BABYLON.CustomProceduralTexture;var FreeCameraGamepadInput = BABYLON.FreeCameraGamepadInput;var ArcRotateCameraGamepadInput = BABYLON.ArcRotateCameraGamepadInput;var GamepadManager = BABYLON.GamepadManager;var StickValues = BABYLON.StickValues;var Gamepad = BABYLON.Gamepad;var GenericPad = BABYLON.GenericPad;var Xbox360Pad = BABYLON.Xbox360Pad;var PoseEnabledControllerHelper = BABYLON.PoseEnabledControllerHelper;var PoseEnabledController = BABYLON.PoseEnabledController;var WebVRController = BABYLON.WebVRController;var OculusTouchController = BABYLON.OculusTouchController;var ViveController = BABYLON.ViveController;var GenericController = BABYLON.GenericController;var WindowsMotionController = BABYLON.WindowsMotionController;var GearVRController = BABYLON.GearVRController;var FollowCamera = BABYLON.FollowCamera;var ArcFollowCamera = BABYLON.ArcFollowCamera;var UniversalCamera = BABYLON.UniversalCamera;var GamepadCamera = BABYLON.GamepadCamera;var PostProcessRenderPipelineManager = BABYLON.PostProcessRenderPipelineManager;var PostProcessRenderEffect = BABYLON.PostProcessRenderEffect;var PostProcessRenderPipeline = BABYLON.PostProcessRenderPipeline;var DepthRenderer = BABYLON.DepthRenderer;var SSAORenderingPipeline = BABYLON.SSAORenderingPipeline;var SSAO2RenderingPipeline = BABYLON.SSAO2RenderingPipeline;var LensRenderingPipeline = BABYLON.LensRenderingPipeline;var StandardRenderingPipeline = BABYLON.StandardRenderingPipeline;var FxaaPostProcess = BABYLON.FxaaPostProcess;var CircleOfConfusionPostProcess = BABYLON.CircleOfConfusionPostProcess;var DepthOfFieldMergePostProcess = BABYLON.DepthOfFieldMergePostProcess;var DepthOfFieldEffect = BABYLON.DepthOfFieldEffect;var DefaultRenderingPipeline = BABYLON.DefaultRenderingPipeline;var GeometryBufferRenderer = BABYLON.GeometryBufferRenderer;var RefractionPostProcess = BABYLON.RefractionPostProcess;var BlackAndWhitePostProcess = BABYLON.BlackAndWhitePostProcess;var ConvolutionPostProcess = BABYLON.ConvolutionPostProcess;var FilterPostProcess = BABYLON.FilterPostProcess;var VolumetricLightScatteringPostProcess = BABYLON.VolumetricLightScatteringPostProcess;var ColorCorrectionPostProcess = BABYLON.ColorCorrectionPostProcess;var TonemapPostProcess = BABYLON.TonemapPostProcess;var DisplayPassPostProcess = BABYLON.DisplayPassPostProcess;var HighlightsPostProcess = BABYLON.HighlightsPostProcess;var ImageProcessingPostProcess = BABYLON.ImageProcessingPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var Bone = BABYLON.Bone;var BoneIKController = BABYLON.BoneIKController;var BoneLookController = BABYLON.BoneLookController;var Skeleton = BABYLON.Skeleton;var SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var HDRTools = BABYLON.HDRTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystem = BABYLON.LensFlareSystem;var PhysicsJoint = BABYLON.PhysicsJoint;var DistanceJoint = BABYLON.DistanceJoint;var MotorEnabledJoint = BABYLON.MotorEnabledJoint;var HingeJoint = BABYLON.HingeJoint;var Hinge2Joint = BABYLON.Hinge2Joint;var PhysicsImpostor = BABYLON.PhysicsImpostor;var PhysicsEngine = BABYLON.PhysicsEngine;var PhysicsHelper = BABYLON.PhysicsHelper;var PhysicsRadialExplosionEvent = BABYLON.PhysicsRadialExplosionEvent;var PhysicsGravitationalFieldEvent = BABYLON.PhysicsGravitationalFieldEvent;var PhysicsUpdraftEvent = BABYLON.PhysicsUpdraftEvent;var PhysicsVortexEvent = BABYLON.PhysicsVortexEvent;var CannonJSPlugin = BABYLON.CannonJSPlugin;var OimoJSPlugin = BABYLON.OimoJSPlugin;var TGATools = BABYLON.TGATools;var DDSTools = BABYLON.DDSTools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var Debug = BABYLON.Debug;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var HighlightLayer = BABYLON.HighlightLayer;var AbstractAssetTask = BABYLON.AbstractAssetTask;var AssetsProgressEvent = BABYLON.AssetsProgressEvent;var MeshAssetTask = BABYLON.MeshAssetTask;var TextFileAssetTask = BABYLON.TextFileAssetTask;var BinaryFileAssetTask = BABYLON.BinaryFileAssetTask;var ImageAssetTask = BABYLON.ImageAssetTask;var TextureAssetTask = BABYLON.TextureAssetTask;var CubeTextureAssetTask = BABYLON.CubeTextureAssetTask;var HDRCubeTextureAssetTask = BABYLON.HDRCubeTextureAssetTask;var AssetsManager = BABYLON.AssetsManager;var SceneSerializer = BABYLON.SceneSerializer;var ReflectionProbe = BABYLON.ReflectionProbe;var Layer = BABYLON.Layer;var TextureTools = BABYLON.TextureTools;var FramingBehavior = BABYLON.FramingBehavior;var BouncingBehavior = BABYLON.BouncingBehavior;var AutoRotationBehavior = BABYLON.AutoRotationBehavior;var EngineInstrumentation = BABYLON.EngineInstrumentation;var SceneInstrumentation = BABYLON.SceneInstrumentation;var _TimeToken = BABYLON._TimeToken;var BackgroundMaterial = BABYLON.BackgroundMaterial;var EnvironmentHelper = BABYLON.EnvironmentHelper;var GridMaterial = BABYLON.GridMaterial;var GLTFFileLoader = BABYLON.GLTFFileLoader;
  91513. export { EffectFallbacks,EffectCreationOptions,Effect,KeyboardEventTypes,KeyboardInfo,KeyboardInfoPre,PointerEventTypes,PointerInfoBase,PointerInfoPre,PointerInfo,Color3,Color4,Vector2,Vector3,Vector4,Size,Quaternion,Matrix,Plane,Viewport,Frustum,Axis,BezierCurve,Angle,Arc2,Path2,Path3D,Curve3,PositionNormalVertex,PositionNormalTextureVertex,Tmp,Scalar,expandToProperty,serialize,serializeAsTexture,serializeAsColor3,serializeAsFresnelParameters,serializeAsVector2,serializeAsVector3,serializeAsMeshReference,serializeAsColorCurves,serializeAsColor4,serializeAsImageProcessingConfiguration,serializeAsQuaternion,SerializationHelper,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,LoadFileError,RetryStrategy,Tools,PerfCounter,className,AsyncLoop,PromisePolyfill,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,EngineCapabilities,Engine,Node,BoundingSphere,BoundingBox,BoundingInfo,TransformNode,AbstractMesh,Light,Camera,RenderingManager,RenderingGroup,RenderingGroupInfo,Scene,KeepAssets,AssetContainer,Buffer,VertexBuffer,DummyInternalTextureTracker,InternalTexture,BaseTexture,Texture,_InstancesBatch,Mesh,BaseSubMesh,SubMesh,MaterialDefines,Material,UniformBuffer,VertexData,Geometry,_PrimitiveGeometry,RibbonGeometry,BoxGeometry,SphereGeometry,DiscGeometry,CylinderGeometry,TorusGeometry,GroundGeometry,TiledGroundGeometry,PlaneGeometry,TorusKnotGeometry,PostProcessManager,PerformanceMonitor,RollingAverage,ImageProcessingConfiguration,ColorGradingTexture,ColorCurves,MaterialHelper,PushMaterial,StandardMaterialDefines,StandardMaterial,PBRBaseMaterial,PBRBaseSimpleMaterial,PBRMaterial,PBRMetallicRoughnessMaterial,PBRSpecularGlossinessMaterial,CameraInputsManager,TargetCamera,FreeCameraMouseInput,FreeCameraKeyboardMoveInput,FreeCameraInputsManager,FreeCamera,ArcRotateCameraKeyboardMoveInput,ArcRotateCameraMouseWheelInput,ArcRotateCameraPointersInput,ArcRotateCameraInputsManager,ArcRotateCamera,HemisphericLight,ShadowLight,PointLight,DirectionalLight,SpotLight,AnimationRange,AnimationEvent,PathCursor,Animation,TargetedAnimation,AnimationGroup,RuntimeAnimation,Animatable,EasingFunction,CircleEase,BackEase,BounceEase,CubicEase,ElasticEase,ExponentialEase,PowerEase,QuadraticEase,QuarticEase,QuinticEase,SineEase,BezierCurveEase,Condition,ValueCondition,PredicateCondition,StateCondition,Action,ActionEvent,ActionManager,InterpolateValueAction,SwitchBooleanAction,SetStateAction,SetValueAction,IncrementValueAction,PlayAnimationAction,StopAnimationAction,DoNothingAction,CombineAction,ExecuteCodeAction,SetParentAction,PlaySoundAction,StopSoundAction,SpriteManager,Sprite,IntersectionInfo,PickingInfo,Ray,Collider,CollisionCoordinatorWorker,CollisionCoordinatorLegacy,Particle,ParticleSystem,BoxParticleEmitter,ConeParticleEmitter,SphereParticleEmitter,SphereDirectedParticleEmitter,SolidParticle,ModelShape,DepthSortedParticle,SolidParticleSystem,ShaderMaterial,GroundMesh,InstancedMesh,LinesMesh,MeshBuilder,AudioEngine,Sound,SoundTrack,Analyser,CubeTexture,RenderTargetTexture,MultiRenderTarget,MirrorTexture,RefractionTexture,DynamicTexture,VideoTexture,RawTexture,PostProcess,PassPostProcess,ShadowGenerator,DefaultLoadingScreen,SceneLoaderProgressEvent,SceneLoader,FilesInput,StringDictionary,Tags,AndOrNotEvaluator,Database,FresnelParameters,MultiMaterial,FreeCameraTouchInput,TouchCamera,ProceduralTexture,CustomProceduralTexture,FreeCameraGamepadInput,ArcRotateCameraGamepadInput,GamepadManager,StickValues,Gamepad,GenericPad,Xbox360Pad,PoseEnabledControllerHelper,PoseEnabledController,WebVRController,OculusTouchController,ViveController,GenericController,WindowsMotionController,GearVRController,FollowCamera,ArcFollowCamera,UniversalCamera,GamepadCamera,PostProcessRenderPipelineManager,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,CircleOfConfusionPostProcess,DepthOfFieldMergePostProcess,DepthOfFieldEffect,DefaultRenderingPipeline,GeometryBufferRenderer,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,BlurPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PanoramaToCubeMapTools,HDRTools,HDRCubeTexture,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,TGATools,DDSTools,KhronosTextureContainer,Debug,RayHelper,DebugLayer,BoundingBoxRenderer,MorphTarget,MorphTargetManager,Octree,OctreeBlock,VRDistortionCorrectionPostProcess,AnaglyphPostProcess,StereoscopicInterlacePostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationGamepadCamera,VRDeviceOrientationArcRotateCamera,AnaglyphFreeCamera,AnaglyphArcRotateCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicFreeCamera,StereoscopicArcRotateCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,HighlightLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,GridMaterial,GLTFFileLoader };